Wait until jquery ajax request is done and return value

Sagar picture Sagar · Mar 6, 2013 · Viewed 15.5k times · Source

I want to wait until ajax call complete and return the value.

function isFileExists(url) {
    var res = false;
    $.ajax({
        type: "GET",
        async: false,
        url: url,
        crossDomain: true,
        dataType: "script",
        success: function () {
            res = true;
        },
        error: function () {
            res = error;
        },
        complete: function () {

        }
    });
    return res; //It is always return false
}

I want to return the value "true/error"

Please help me.

Answer

Explosion Pills picture Explosion Pills · Mar 6, 2013

You can't do this. That's not how ajax works. You can't depend on the ajax request completing at any given time ... or ever completing. Any work you need to do that is based on the ajax request must be done in the ajax callbacks.

jQuery makes it easy to bind callbacks (because jqXHR returned by jQuery's ajax methods implements Deferred):

var jqXHR = $.ajax({/* snip */});

/* millions of lines of code */

jqXHR.done(function () {
    console.log('true');
}).fail(function () {
    console.log('false');
});

P.S. you can do what you want to do if you set async to false, but that locks up the browser while the request runs. Don't do it. Then you just have jax.

EDIT: You can't combine crossDomain: true and async: false. Cross Domain must be asynchronous.