4

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.

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
Sagar
  • 259
  • 2
  • 3
  • 14
  • 1
    consider using jquery tag instead of javascript next time, its gonna make it more specific and save people time. Thank You – Toping Mar 06 '13 at 13:25

3 Answers3

10

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.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
0

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.

net892z
  • 61
  • 4
  • Yes it should be called until the ajax request has been resolved. Try adding the 'timeout' setting to the ajax call, setting it to 1 minutes (maybe), as means to escape. – net892z Mar 06 '13 at 14:20
0

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) {

            }
        });
    }
Prince Prasad
  • 1,528
  • 1
  • 16
  • 20