I have the following code within the ajax success function.
$.each(data,function(index,element){
$.ajax({
type: 'GET',
url: "http://192.168.1.56/SampleAjaxCall/sample.svc/sampleFunciton",
contentType: 'application/json; charset=utf-8',
dataType: 'jsonp',
async: false,
success:function(response){
alert("Success !"); // invokes after the loop
}
});
alert("After the ajax call"); // invokes first
});
First i am getting this alert message After the ajax call. after the loop end i am getting this alert message alert("Success !"). So the ajax is invoked after the loop end. So i need to invoke the ajax first. How to achieve this scenario.
Actually, your ajax call is in fact invoked before the second alert message ("After the ajax call"). But, as AJAX stands for Asynchronous etc. etc, while the ajax request is being processed, the rest of the script is executed already. So if you want the code being executed after the ajax call, wrap it in a function, and call that function in the success block (or just move the code into the success callback). Example:
var after_call_func = function() {
alert("After the ajax call");
};
$.each(data,function(index,element){
$.ajax({
// your ajax configuration
success:function(response){
alert("Success !");
after_call_func(); // call the function when ajax is complete
}
});
});
EDIT
I now notice you have the async option set to false, which is most probably why you'd expect the alert to execute AFTER the ajax call in the first place... But, as the jQuery documentation tells us:
Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.
And it looks like you have both... So either don't use a jsonp datatype nor a cross-domain request, or wrap the code to be executed after the ajax call in the success block, as in the example above.
According to jQuery.ajax docs, dataType: "jsonp" requests do not support synchronous operation, so async: false is not going to work. You need to do it as giorgio describes.
Related
I am trying to load from a PHP file using ajax, some JSON objects but my problem is that my javascriptcode is not working on the correct order. Here is my code:
var requests;
$(document).ready(function(){
setInterval(function(){
$.ajax({
url: "test2.php",
success: function(result){
requests = JSON.parse(result);
alert(requests);
}
});
})
});
alert(requests);
Here is the first alert i'm getting on page load and here is the second alert
My question is why the alert in the last line is executed before the ajax
Note: this is a small example of my project, my real error is that i cannot load some arrays i need using ajax, because it shows as undefined at console, even if the ajax is in the beginning of the script.
try this cod for ajax call with php
$.ajax({
type: "method", // post or get
url: "file url",
dataType: "json",
success: function(data){
},
error: function(){
}
});
The best way to avoid this is to create a function in which second alert would be placed. And call this function inside ajax call's success method.
e.g.
ajax({
...
success: function(){
...
secondAlert();
};
...
});
function secondAlert(){
alert("alert after jax call");
};
As for
My question is why the alert in the last line is executed before the ajax
AJAX is an acronym for Asynchronous JavaScript and XML. The keyword here is asynchronous. AJAX sends the HTTP request and keeps executing the code in async fashion. The callback function of the AJAX request is executed after the request is finished and the corresponding response has been received. More info is available here
sometimes even if the ajax call has returned error, it calls done() chain function rather than fail().
so confused whether to use success/error callback or done()/fail() chain function.
for eg which one is advisable 1 or 2?
$.ajax({
url: someurl,
success: function(){
//some code if ajax request is successful
},
error: function(){
//some code if ajax request fails
}
})
$.ajax({
url: someurl
}).done(function(){
//some code changes
}).fail(function(){
//some code changes
});
These are interchangeable ways of doing an AJAX call in jQuery. The second method you describe uses promises, whereas the first method handles successes/errors as options on the AJAX call.
I am pretty much new to ajax and working on jquery ajax request. Ajax callback is not calling success method. Interaction is between cross-site domains.
My AJAX request looks like
$.ajax({
timeout: 20000,
url: 'test.com',
crossDomain: true,
dataType: 'jsonp',
success: function (data) {
console.log('callback success');
this._cache = data;
localStorage.token = data.access_token;
} });
There are no errors in this call.
This ajax request is not calling success function.Request is returning json data. it's just success method is not getting called.
This ajax request is not calling success function.
Get request is getting fired successfully. I can even trace the response in fiddler with 200 http response.For some reason success method is not getting called.
it's returning json object, which I've traced in fiddler
You're telling jQuery to expect a JSONP response, so it is trying to execute the JSON document as if it were a JavaScript script (because that is what JSONP is). This fails because it is not JSONP.
Either return JSONP instead of JSON or (assuming the server returns the correct Content-Type) remove dataType: 'jsonp',.
ok... I came here with the same problem... and when I read that specifying datatype:jsonp never calls success as a callback per #mondjunge from a comment above, it started me thinking about some behavior I saw earlier from my code and that maybe datatype:json might have the same behavior for what ever reason here too.
So after reading this page I took out my datatype declaration from my ajax request and my servlet returned the proper data payload, returned a 200, and jquery called the success function finally and modified my DOM.
All those steps happened except the last one until I removed my datatype from my ajax call. NOT what I was expecting!
Hopefully someone else can shed some light on why this happens... for now at least the few that don't lose their minds to this issue that find this post can do this in the mean time.
Check if your ajax is executed
Check it's status. If response code is != 200, than you should add error method also, for error handling.
Try this:
$.ajax({
timeout: 20000,
url: 'test.com',
method: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function (data) {
console.log('callback success');
this._cache = data;
localStorage.token = data.access_token;
},
error: function(xhr, error){
console.debug(xhr); console.debug(error);
},
});
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is it posible to use ajax respone outside of it?
I've created the following JavaScript routine that goes to a WCF oData service and gets some data. In the success element I get the results into the results variable and alert them - I see that there are objects returned. When I run the second alert, outside of the ajax call and before returning the results, the results variable is "undefined".
Can anyone please tell me where I'm going wrong?
function retrieveJsonpODataSet(baseUrl, query)
{
var oDataUrl = baseUrl + "?$format=json&$callback=?";
var results;
$.ajax(
{
url: oDataUrl,
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'jsonp',
async: false,
success:
function (data, textStatus, xhr)
{
results = data.d;
alert(results); // This shows the results
},
error:
function (xhr, textStatus, errorThrown)
{
alert("Query failed.\n\n" + oDataUrl + "\n\n" + errorThrown);
results = null;
}
});
alert(results); // This shows "undefined"
return results;
}
Please ignore the query parameter - I've not finished the routine yet.
EDIT
Initially I had no async:false in the ajax call. I've added that now but it doesn't fix the problem.
The ajax call is an asynchronous operation. It fires and your code does not stop at it. So results is returned which at that point is undefined. What you need to do is to pass callback to the function.
function retrieveJsonpODataSet(baseUrl, query, callback) {
/* some code */
$.ajax({
/* some settings */
success: function(res) {
/* some code */
callback(results);
}
});
}
Now you use it like this
retrieveJsonpODataSet(baseUrl, query, function(res) {
/* Hurray, I have result now in res variable! */
});
DO NOT USE async: false OPTION! It blocks ALL scripts untill the call finishes... and what if it does not finish at all?? You will be blocked forever.
EDIT
I've missed that the request is JSONP. In that case async: false won't even work (it does not work for cross-domain requests and JSONP). So you have to use callbacks anyway.
A fellow Richard!
This isn't a scope issue, but more of an execution one. Both the success and error options are event handlers, and run asynchronously (hence it being called AJAX). This essentially means that the alert(results) and return results can, and likely will, get executed before the success or error events are triggered.
Your ajax is async, so the alert executes before the ajax completes. You need to set the ajax call async property to false in order for script to halt the execution until ajax request is made & processed.
However, jQuery docs says:
async
Default: true
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false is deprecated.
AJAX request are sent, without the script waiting for a response, that's what Dave Newton means by A-synchronus, put the alert inside the success callback function, and you'll see what the actual response is.
alternatively, you can specify the async property, and set it to false, to force your script to wait for the response, before continuing.
If I make an ajax call to a controller.... what needs to happen in the controller so that the ajax call then calls
1) complete:
2) success:
3) error:
4) any other callbacks that exist.
For ex. I have this ajax call.
$.ajax({
url: "/ContactPartial/ContactUs",
type: "POST",
data: JSON.stringify(data),
dataType: 'json',
contentType: "application/json; charset=utf-8",
complete: function () { },
success: function () { },
error: function () { }
});
In other words, what can I do inside /ContactPartial/ContactUs to control which of the 3 (complete,success,error) gets called after the controller code executes.
Also, how is this related to related to return Json(new {some: data});
These three callbacks are related to the status of the Ajax call. These are called depending on success of the call. For complete details refer to the documentation
So, if the server responds with a success (200), then both the Success and the Complete handlers would be called. In the complete handler, you might put some code to dismiss a modal window (regardless of success or error), and in the success function, you might put code to let the user know the call was successful, reload a grid view, etc. Also, keep in mind that the callback functions don't have to be anonymous functions, they can be defined functions that are shared among several Ajax calls.
EDIT:
If you are wanting to force the server to generate an error, take a look at:
The HttpResponse class, specifically the StatusCode property
This SO post explains more too (generating a 401 error)