I have 4 scripts which I want to call one after another through ajax.
I want to call script_2 only after script_1 has completed execution.
It means first I want to call script_1 in ajax, display the result of script_1 execution in its respective div and then call second script, show its result in second div and so on.
Currently what I am doing is creating a new ajax call inside the onreadystatechange() function (in a nested way).
Below is the pseudo-code:
var script1_ajax = new XMLHttpRequest();
script1_ajax.onreadystatechange=function() {
if (script1_ajax.readyState==4 && script1_ajax.status==200) {
document.getElementById('result').innerHTML = script1_ajax.responseText;
//create second ajax request and call it
//similarly create two more nested ajax calls and call it
}
}
I don’t think this is the proper way of doing this.
Please suggest how to do this in a less complicated way.
Likely your best option is using a Javascript library, for example jQuery. jQuery has the
jQuery.Deferred()object which can be used to easily represent a promise (a future result) thus allowing easy chaining of function calls. Note that$.get(), for example, returns aDeferred(see the documentation below in the page). This article also has a nice solution and a working jsfiddle, but it quites diverges from theDeferredapproach, which is simply a matter ofIf you don’t know jQuery,
$.get(url, params, callback)is the way to make asynchronous HTTP GET requestsNote: I updated the code, since
deferred.then()requires a callback (I gave it a promise) and replacedthen()withpipe(), which gives the intended behavior on current jQuery versions (actually in 1.8 it seemsthen()is an alias to the currentpipe())