Sagar
Sagar

Reputation: 269

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.

Upvotes: 4

Views: 17692

Answers (3)

Prince Prasad
Prince Prasad

Reputation: 1678

Try this code. it worked for me.

 function getInvoiceID(url, invoiceId) {
        return $.ajax({
            type: 'POST',
            url: url,
            data: { invoiceId: invoiceId },
            async: false,
        });
    }
    function isInvoiceIdExists(url, invoiceId) {
        $.when(getInvoiceID(url, invoiceId)).done(function (data) {
            if (!data) {

            }
        });
    }

Upvotes: 0

net892z
net892z

Reputation: 61

maybe this will work for you:

function isFileExists(url, init) {
    var res = null;
    var _init = init || false;

    if (!_init) {
        _init = true;
        $.ajax({
             type: "GET",
             url: url,
             crossDomain: true,
             dataType: "script",
             success: function () {
                 res = true;
             },
             error: function () {
                 res = 'error';
             },
             complete: function () {

             }
        });
    }

    if (res==null) {
        setTimeout(function(){ isFileExists(url, _init); }, 100);
    } else {
        return res;
    }
}

I tested it briefly, but not cross domain.

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191749

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.

Upvotes: 10

Related Questions