I am new to jQuery and am having trouble following the documentation. I have a variable in JavaScript (that I already obtained from an html form) that I would like to send using AJAX to the server. I want to the server to do whatever it needs to do with that value and then reply with either "success" or "failure" (I know how to do the backend part). How do I send the request and then receive the reply with jQuery?
To send the request you use the $.post or $.get function (or the $.ajax function if you want loads of control)
$.post('example.com/script', {
'param1':somaVar
}, function(data){
alert(data); //data is whatever the server returned
});
For both $.get and $.post the argument order is like this: (url, [data], [callback], [type]). Url is the url to which the request is done, data is the data with which the request is send, callback is a function that is executed when the request is complete. Type is the type of data the server will return (jQuery usually finds this out on itself) possibles are "xml", "html", "script", "json", "jsonp", or "text"
Related
I am looking for a method to create a dynamic dependent select box in a JSP, preferably something AJAX/JQuery based so I don't have to make a separate trip to the server. I am updating an internal auditing page for my organization and adding a feature to allow for a 're-audit'. The first select box is populated on page load and is listing of all employees and the second, populated dynamically, should be a listing of the previous audits for the selected employee.
Try something like this in your javascript (do not forget to import latest stable version of jquery),
$(document).ready(function() { //This will be triggered on page ready
jQuery.ajax({
type: "POST", //Passing data in post method
url: "ServletURL", //Servlet URL
data: "userId=" + $("#userId").val(), //Post if you need to send anything
success: function (response) { //Ajax success data
alert("Details loaded successfully!!!");
},
error: function (xhr, ajaxOptions, thrownError) { //Ajax failure data
alert(xhr.status);
alert(thrownError);
}
});
});
And process the userId in servlet and transfer the resulted data into any jsp page, where you can convert your result into the type either json or xml for your comfort. This data will be returned as response in ajax success.
I am getting errors on callBacks. I have tried following code in jsfiddle.com . You can also try. Data from servelet is not returning. It's returning same error again and again. Check jquery library when you try in jsfiddle
$.ajax({
url : 'http://192.168.16.111:8081/MiddleWareUsman/androidServlet',
type : "post",
dataType: "jsonp",
data : {
"fname": "chaaaaapiio",
"lname": "gya"
},
success : function(data) {
alert("hello"+data);
},
error : function(xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
My server side:
String a=request.getParameter("fname");
String b=request.getParameter("lname");
response.getWriter().write(a+" "+ b);
It appears you have a couple problems.
JSONP requests can't be sent via POST. They are actually sent as <script> tag requests anyway which are GET requests.
Your server isn't doing JSONP. For the server to do JSONP, it must wrap the requested data in a call to a javascript function who's name was passed as an argument to the request and then the actual data is passed as an argument to that function. JSONP is a big hack, but it works by requesting a javascript and that's what the server must return.
you simply can't send a POST request using JSONP
check this link out to see how JSONP works..
I need to test the browser window width in JSP, to determine whether or not I have to set a value in the request object. Typically I would achieve this with something like this:
if(document.body.offsetWidth < xxxx){
// ...
}
But I don't know how to do it with a JSP expression.
You might misunderstand that jsp and javascript existed on same file. Yes but JSP part compiles on server side itself comes to client.
You can't do that with JSP.
JSP compiles on serverside Where as javascript plays on browser i.e on client side.
Do it with javascript.You should do it in document load
when you do if(document.body.offsetWidth < xxxx) you are doing it at client side. Now if you want to propagate some client side value to server side i.e to some java class(most of the cases it will be servlets) then you have two options:-
1)Make an AJAX call. (You can also use jquery here to make AJAX call).
Here is the small example, you can find ample on google
$.ajax({
type: 'GET',
dataType: 'json',
data: { windowWidth: "100"}
url: servlerURL,
success: function(reply) {
},
error: function (xhr, textStatus, errorThrown) {
}
});
or
2)Submit the form
Trying to send a simple text from my rest service and read it using ajax call. Found many answers about jsonp and cross browser compatibility, tried crossdomain too.
Here is the rest service:
Trimmed everything down to send only a simple string.
#GET
#Path("/getcontents2")
#Produces({MediaType.TEXT_PLAIN})
public String getContents2(#QueryParam("name") String msg) {
return "abc";
}
The ajax call:
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'http://metrics/getcontents2?name=Work/loc.txt',
crossDomain: true,
async: false,
dataType:'html',
success: function (data) {
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
console.log(xhr.responseText);
console.log(xhr);
},
});
});
The browsers opens up the string as is. I guess something is really wrong in the jquery script.
Error on Firebug:
GET http://metrics/getcontents2?name=Work/loc.txt 200 OK 4ms
0
(an empty string)
(an empty string)
Object { readyState=0, status=0, statusText="error"}
Fixed it!
It was because my server was not supporting cross-domain. Configured it will corsfilter and it worked like a charm!
try setting your datatype to text jsonp
dataType: 'jsonp',
http://api.jquery.com/jQuery.ajax/
You will have to do one of two things to go with this to resolve the error further;
making changes on the server side to pass the data back as json and not as text
retun the string encoded in json return "{"text":"abc"}"; //or something like this
Why?
jquery cross-domain requests are only allowed for dataTypes "script" and "jsonp".
I have updated your fiddle it still throws an error but that is related to a parse json error
I need to send large amount of string in a ajax post request to server. If i add it the end of the url, i can get using request.getParameter() method in the server.
But i can't append large string in the url.So i want to send using the method send() of XMLHttpRequest instead of appending it to url.
But i couldn't retrieve the same using request.getParameter() in server.
How to retrieve data send from ajax request in j2ee server?
Please guide me.
If you have an ajax intensive webapp, I would suggest using a javascript library (such as jquery) to handle ajax. In jQuery, you could do this as :
$.post("your_url.php", { param1: "value1", param2: "value2" } );
Regardless of whether you are or arent using AJAX, there are limits to the actual length of the Url which changes browser to browser.
It will be better POST all your data. Below is the code to do the same using AJAX:
var http = new XMLHttpRequest(); // Get the correct http object depending on browser
var url = "YOUR_URL.php";
var params = "param1=value1¶m2=value2";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() { // Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
Hope this helps.