Servlet Code
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String s = request.getAttribute("stopName").toString();
response.getWriter().write(s);
}
Ajax Code
function makeRequest(i) {
var stopName = document.getElementById('newStopName' + i).value;
var Longitude = document.getElementById('newLongitude' + i).value;
var Latitude = document.getElementById('newLatitude' + i).value;
var Description = document.getElementById('newStopDesc' + i).value;
document.getElementById('hidnewStopName' + i).value = stopName;
document.getElementById('hidnewLongitude' + i).value = Longitude;
document.getElementById('hidnewLatitude' + i).value = Latitude;
document.getElementById('hidnewStopDesc' + i).value = Description;
var xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
xmlHttpRequest.open("GET", "Edit_Route", true);
xmlHttpRequest.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlHttpRequest.send("stopName="+encodeURIComponent(stopName));
}
/*
* Returns a function that waits for the state change in XMLHttpRequest
*/
function getReadyStateHandler(xmlHttpRequest) {
// an anonymous function returned
// it listens to the XMLHttpRequest instance
return function() {
if (xmlHttpRequest.readyState === 4) {
if (xmlHttpRequest.status === 200) {
alert(xmlHttpRequest.responseText);
} else {
alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
}
}
};
}
i want send StopName and and again send to client using ajax please help me using javascript not jquery.Actually i want send data and save it to database that s way i want test it
I think this might be come because u have get parameter in wrong way.
String stopName = request.getParameter("stopName") != null ? request.getParameter("stopName").toString() : "null value";
it will also handle the null condition.
try this code.
Is the servlet path correct in ajax code ?
I mean "/Edit_Route" not "Edit_Route"
Maybe the ajax can not found your servlet ,i think
Related
I am making an application which would be able to count the numbers written in formulas. In html I have put this:
<input type="text" size="20" id="number2" onblur="validate2()"
onFocus = "document.getElementById('msg2').innerHTML = ' '">
<br>
<div id = "message1"> </div>
I have created a javascript which is firstly validating the datas and later inserts them into the 'answer-formula':
function validate2() {
var idField2 = document.getElementById("number2");
var data2 = "number2=" + encodeURIComponent(idField2.value);
if (typeof XMLHttpRequest != "undefined") {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "Validator"
req.open("GET", url, true);
req.onreadystatechange = inserter2
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
;
req.send(data2);
}
function inserter2() {
if (req.readyState == 4) {
if (req.status == 200) {
var msg1 = req.responseText
if (msg1 == "") {
document.getElementById("message1").innerHTML = "<div style=\"color:red\">Zła nazwa</div>";
document.getElementById("org").value = ''
}
else
document.getElementById("org").value = msg2
}
}
}
And here's my code in which is sending it as doGet:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("GET");
response.setContentType("text/html");
Writer out = response.getWriter();
String num2 = request.getParameter("number2");
System.out.println(num2);
String org = new String();
if(num2.matches("[\\p{Punct}\\d]+")) {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
try {
org = engine.eval(num2).toString() + " (" + request.getMethod() + ")";
} catch (Exception e) {
e.printStackTrace();
}
}
out.write(org != null ? org : "");
}
If we change all these things into the Post, this code will work, but now as it is with GET, it doesn't work at all. Another strange situation is that the formula with POST can read the written things in formula, but as we are using GET, the program see formula source as null.
If you send it as get, you need to put formula into request. This expression:
req.send(data2);
doesn't make sense when you send GET request, as GET request cannot contain any payload except in request string. So you have to add payload to your url. Something like this:
var url = "Validator/?" + data2;
req.open("GET", url, true);
req.onreadystatechange = inserter2;
req.send();
Hope that helps.
So I have a tomcat server that I can successfully send a query such as... localhost:8080/AnarchyChatServer/AnarchyChatServlet?message=asdf&sendto=x&sendfrom=y
This will run the doGet() in my tomcat server, I have nothing in doPost()
Which will simply return asdf x y in the response BODY as HTML. Now in my C# I am trying to build the query string and send the message as such...
public string sendMessage(string message)
{
string url = "";
string response = "No server response.";
using (var wb = new WebClient())
{
UriBuilder baseUri = new UriBuilder("localhost:8080/AnarchyChatServer/AnarchyChatServlet");
message = message.Replace("&", "(AMPERSAND)");
message = message.Replace("?", "(QUESTIONMARK)");
string queryToAppend = "message=" + message;
if (baseUri.Query != null && baseUri.Query.Length > 1)
baseUri.Query = baseUri.Query.Substring(1) + "&" + queryToAppend;
else
baseUri.Query = queryToAppend;
url = baseUri.Uri.ToString();
queryToAppend = "sendto=" + sending;
if (baseUri.Query != null && baseUri.Query.Length > 1)
baseUri.Query = baseUri.Query.Substring(1) + "&" + queryToAppend;
else
baseUri.Query = queryToAppend;
url = baseUri.Uri.ToString();
queryToAppend = "sentfrom=" + account[0];
if (baseUri.Query != null && baseUri.Query.Length > 1)
baseUri.Query = baseUri.Query.Substring(1) + "&" + queryToAppend;
else
baseUri.Query = queryToAppend;
url = baseUri.Uri.ToString();
try
{
response = wb.DownloadString(baseUri.Uri);
}
catch (System.Net.WebException)
{
}
}
return response;
}
Ignore the hideous code reuse and whatnot. Basically the query building seems to work correct as if I output "url" it will return the proper url with the query string, but the issue is is that when I print out response after the call has been made to the server it just says "No server response" as it was initialized at the top of the C# code. Basically I'm wondering how I can query the server. Any insight would be helpful.
Your first problem is the lack of protocol in the Uri. Try this:
UriBuilder baseUri = new UriBuilder("http://localhost:8080/AnarchyChatServer/AnarchyChatServlet");
By the way... To debug these issues in the future, use:
catch (Exception ex)
{ <- breakpoint here
}
And examine ex. Or turn on breaking on thrown CLR exceptions in Visual Studio and debug the code (or just don't swallow the exception). Then you would see this:
Ignoring exceptions when debugging code is not a good idea in general...
I am trying to fetch page content with phantomjs. In many examples on the official site (eg.: https://github.com/ariya/phantomjs/blob/master/examples/imagebin.js) the function page.open() is used.
In my script though it does not seem to work. I used reflection to look at all defined methods of the page object:
for ( var prop in page) {
if (typeof page[prop] == 'function') {
log("method in page: " + prop);
}
}
and the open() method did not show up. (close(), render(), etc... did show up)
also when I am trying to execute a script:
// include plugins
var system = require('system');
var fileSystem = require('fs');
var page = require('webpage').create();
// global errorhandler
phantom.onError = function(msg, trace) {
console.log("ERROR!!!!! \n" + msg);
phantom.exit(1);
};
// read json input and remove single outer quotes if set
var jsonin = system.args[1];
if (jsonin.charAt(0) == "'") {
jsonin = jsonin.substr(1, jsonin.length - 2);
}
// make object of json
var data = eval('(' + jsonin + ')');
// optional url
var url = system.args[2];
// transfer file
var dest = system.args[3];
console.log("systemargs[1]: data -> " + data);
console.log("systemargs[2]: url -> " + url);
console.log("systemargs[3]: dest -> " + dest);
openRoot();
/*
* open site
*/
function openRoot() {
page.onConsoleMessage = function(msg) {
console.log('INNER ' + msg);
};
page.open(url, function(status) {
if (status === "success") {
if (loadCount == 0) { // only initial open
console.log("opened successfully.");
page.injectJs("./jquery-1.8.3.min.js");
} else {
console.log("page open error.");
console.log('skip refresh ' + loadCount);
}
} else {
console.log("error opening: " + status);
}
});
}
phantom.exit(0);
it does not execute the open function. The log does not show any messages inside the open() method.
Any advice on what I might do wrong would be greatly appreciated. If there is additional information required, please let me know.
Regards,
Alex
Edit:
The line
console.log(typeof (page.open));
outputs: function which is not what I expected, given the previous list of methods I wrote to the log, where open does not exist. Hmm.
After hours of senseless searching I found the mistake. Stupid me. At the end of the script I call phantom.exit() where I should not.
The working code includes an Interval which checks on an object, in my case content and a member of that content.isFinished. If I set this to true, then phantom.exit() gets called.
My bad, absolutely my fault.
Working code:
var url = system.args[2];
// transfer file
var dest = system.args[3];
content = new Object();
content.isFinished = false;
console.log("systemargs[1]: data -> " + data);
console.log("systemargs[2]: url -> " + url);
console.log("systemargs[3]: dest -> " + dest);
openRoot();
/*
* open site
*/
function openRoot() {
page.onConsoleMessage = function(msg) {
console.log('INNER ' + msg);
};
page.open(url, function(status) {
if (status === "success") {
if (loadCount == 0) { // only initial open
console.log("opened successfully.");
page.injectJs("./jquery-1.8.3.min.js");
// do stuff
content.isFinished = true;
} else {
console.log("page open error.");
console.log('skip refresh ' + loadCount);
content.isFinished = true
}
} else {
console.log("error opening: " + status);
}
});
}
/*
* wait for completion
*/
var interval = setInterval(function() {
if (content.isFinished) {
page.close();
f = fileSystem.open(dest, "w");
f.writeLine(out);
f.close();
// exit phantom
phantom.exit();
} else {
console.log('not finished - wait.');
}
}, 5000);
Regards,
Alex
my data:
var test = {cars : []};
var cars = []
cars.push({
"name" : "Ford",
"year" : "2000"
});
cars.push({
"name" : "Audi",
"year" : "2002"
});
test.cars = cars;
var json = JSON.stringify(test);
$.get('/myservlet/', json, function(data) { // also tried .getJSON , .post
alert('Success');
})
In Java I get the "json" variable as parameter key, but no value.
public void doPost(...) // TRIED BOTH
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
for(Object a : req.getParameterMap().keySet()) {
System.out.println(a + " - " + req.getParameter((String)a));
}
//prints out
{"cars":[{"name":"Ford","year":"30"},{"name":"Audi","year":"2002"}]} -
This is unusable result, because the key is always changing, and is ridiculous to for-loop the params everytime. I need to have a specific key : req.getParameter("cars")
Change it to:
$.get('/myservlet/', 'cars='+ json, function(data) { // also tried .getJSON , .post
alert('Success');
You shouldn't have stringified the JSON at all. The whole JSON object test is supposed to be treated as the request parameter map. Just pass the JSON object unmodified.
$.get('/myservlet/', test, function(data) {
// ...
});
This way it's available in the servlet as follows:
for (int i = 0; i < Integer.MAX_VALUE; i++) {
String name = request.getParameter("cars[" + i + "][name]");
if (name == null) break;
String year = request.getParameter("cars[" + i + "][year]");
// ...
}
Update
Your question could be possible duplicate of
READ JSON String in servlet
Previous answer
I assume you are trying to post JSON to the servlet, if thats the case read on.
You would have to check for request body instead of request parameter. Something like
BufferedReader buff = req.getReader();
Check if this works for you
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
BufferedReader buff = req.getReader();
char[] buf = new char[4 * 1024]; // 4 KB char buffer
int len;
while ((len = reader.read(buf, 0, buf.length)) != -1) {
out.write(buf, 0, len);
}
}
Note that I have checked the above code for syntax errors. I hope you get the idea.
I have a REST Server in Java JAX-RS and an HTML page.
I want to send a JSON array, a username, and an accountID from the HTML page through an xmlhttp POST request by making all of them a single big String so I can use the xmthttp.send() method.
The HTML sending code is:
function sendData() {
var req = createRequest();
var postUrl = "rest/hello/treeData";
var dsdata = $("#treeview").data("kendoTreeView").dataSource.data();
var accID = "onthespot";
var username = "alex";
req.open("post", postUrl, true);
req.setRequestHeader("Content-type","text/plain");
req.send("data=" + JSON.stringify(dsdata) + "&username=" + username + "&accID=" + accID);
req.onreadystatechange = function() {
if (req.readyState != 4) {
return;
}
if (req.status != 200) {
alert("Error: " + req.status);
return;
}
alert("Sent Data Status: " + req.responseText);
}
}
And the Server JAX-RS code is:
#Path("/treeData")
#POST
#Consumes(MediaType.TEXT_PLAIN)
#Produces(MediaType.TEXT_PLAIN)
public String storeTreeData(
#QueryParam("data") String data,
#QueryParam("username") String username,
#QueryParam("accID") String accID) {
System.out.println("Data= " + data + "\nAccID= " + accID + "\nUsername= " + username);
return "Done";
}
The problem is that all the variables are printed as null..
the storeTreeData function should find the data , username , accID variables through #QueryParam and store them isn't that right?
Anyone know what's the problem here?
PS:The xmlhttp request is initiallized correctly and the connection is made but the parameters are not passed on the server.
What you try to do:
#QueryParam is used to get parameters from the query of the request:
http://example.com/some/path?id=foo&name=bar
In this example id and name can be accessed as #QueryParam.
But you are sending the parameters in the body of your request.
What you should do:
To get the parameters from the body, you should use #FormParam together with application/x-www-form-urlencoded:
#Path("/treeData")
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Produces(MediaType.TEXT_PLAIN)
public Response storeTreeData(
#FormParam("data") String data,
#FormParam("username") String username,
#FormParam("accID") String accID) {
// Build a text/plain response from the #FormParams.
StringBuilder sb = new StringBuilder();
sb.append("data=").append(data)
.append("; username=").append(username)
.append("; accId=").append(accID);
// Return 200 OK with text/plain response body.
return Response.ok(sb.toString()).build();
}
Edit:
You should also use
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
in your JavaScript code.