I have the following scenario in my javascript:
I am using the when
so that when #2 is complete, I can load the form values from #1. The problem is, is that it appears that when doesn't wait for the success handler to finish, only the ajax call itself. I need to wait for the success function of #2 to complete (as this is what created the form in the DOM) before I can continue with loading the form with values.
If I add an alert1
at step #2, it works (which I'm guessing is because it is waiting for the alert to be clicked, and in that time, the success handler has finished.
If you don't want the $. ajax() function to return immediately, set the async option to false : $(". my_link").
success() only gets called if your webserver responds with a 200 OK HTTP header - basically when everything is fine. However, . complete() will always get called no matter if the ajax call was successful or not - maybe it outputted errors and returned an error - . complete() will still get called.
You can check when exactly it returns "success" : // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { ... // If not modified if ( status === 304 ) { statusText = "notmodified"; ... // If we have data } else { try { ...
Yes, it is deprecated in jQuery 1.8 onwards. You should use . done() and use . fail() to catch the errors.
Do something like this where you use nested functions in the success
callback:
$.ajax({
url: "somewhere"
success: function(data1){
//Use data1 to determine ajax request #2
$.ajax({
url: "somewhere else"
success: function(data2){
//Do stuff with data1 and data2
}
});
}
});
You should use when
or success
not both. It sounds like (although code samples would make this clearer) you are attaching two separate listeners to the ajax call, but you only want one to execute after the other.
I'd either roll both into one event like:
$.ajax( ... , function(){
// success
// prep stuff here
$.ajax( ... , function(){
// second success
// do final stuff here
});
});
Or wrap you ajax call inside another promise (this may require a bit more reading around jQuery promises).
But if you do something like
$.when($.ajax( ... , function(){
// thing a
}).then(function(){
// thing b
});
Thing a and b will execute at the same time, because they are designed for pretty much the same thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With