Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait until jquery ajax request is done and return value

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.

like image 485
Sagar Avatar asked Dec 26 '22 08:12

Sagar


1 Answers

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.

like image 113
Explosion Pills Avatar answered Dec 29 '22 12:12

Explosion Pills