Need to wait until XMLHttpRequest completes

3.6k views Asked by At

Whenever I try to find answer of this question everyone refers to ajax start/stop etc.

I am using XUI JS's XHR function for cross domain calling, now I want exactly like this

callMyXHRfunction();
callNextFunctionWhenAboveFunctionResponded();

i.e. I should move forward until unless my xhr function responds (either success or failure)

Update

Use Case:

There is a function called getAllData(), this function get all my current data submitted to server. I need to call this function often to get the latest data and move ahead. While loggin I call this function to get latest data and after every 10 mins I need to call this to get data refreshed.

So if I call each my function on success function then my code may confuse other developer and if I write like above he/she will easily know what is going on in first line and in 2nd line.

Hope now everyone understand my situation very well.

2

There are 2 answers

7
Henrik Mühe On

See third example on the website you are referencing:

x$( selector ).xhr( url, fn );

Second argument can be a callback, callback being the keyword you were probably looking for to begin with.

Alternatively, use a synchronous call by supplying async: false as an option.

x$("body").xhr("http://the-url",{ async: false });

Control flow will pause until the request returned and only then continue with your next function. See http://jsfiddle.net/ZQ9uw/ for reference.

4
Jon On

You need to make the .xhr call in a way that specifies a callback function and pass in your "next" function as the callback.

So you'd write it like this:

callMyXHRFunction(nextFunctionToCall); // no parens after nextFunctionToCall!

function callMyXHRFunction(callback) {
    $("something").xhr(url, {
        error: callback, // so that nextFunctionToCall is called on error
        callback: callback, // so that nextFunctionToCall is called on success
        async: true
        // add more options here
    });
}