ajax synchronous call with timeout

16,260

Solution 1

Basically, during a synchronous ajax request, the browser is blocked and no javascript can be executed while the browser is blocked. Because of this, jQuery can't abort the ajax request after a set timeout because jQuery is javascript and javascript can't be executed while the browser is blocked. This is the primary flaw in synchronous ajax.

Anytime you might want a synchronous request, you should instead use an asynchronous one with what should happen afterwards in the callback, as shown below;

$.ajax({
    url : 'webservices.php',
    timeout: 200,
    dataType : 'json',
    data : {
        'cmd' : 'ping',
    },
    success : function(data, textStatus) {
        $.ajax({
            url : 'webservices.php',
            async: false,
            dataType : 'json',
            data : {
                'cmd' : 'feedback',
                'data' : data,
                'userinfo' : window.dsuser
            },
            success : function(data, textStatus) {
                // success!
                Status("Thanks for the feedback, "
                    + window.dsuser.user + "!");
            }
        });
    },
    error : function(jqhdr, textStatus,
                     errorThrown) {
        Status("There was trouble sending your feedback. Please try again later");
    }
});

Solution 2

I don't believe it's possible to set a timeout on a synchronous call. When you set "async:false", I believe the browser actually locks up while waiting for the response. You should only use a synchronous request if you absolutely need to (because of the browser locking up).

Share:
16,260
Zoom Pat
Author by

Zoom Pat

Updated on June 11, 2022

Comments

  • Zoom Pat
    Zoom Pat almost 2 years

    New to ajax, so asking a very basic question.

    -- Is there no way to make a Synchronous ajax call (async:false) with timeout set on it.?

    http://www.ajaxtoolbox.com/request/

    Timeout works perfect with Asynchronous call though in my application, but for one particular scenario, I need a Synchronous call (the javascript should actually wait untill it hears back from the server), and this also works fine. But I need to handle a scenario where the sever could take long and a ajax timeout may be called.

    Is there any other piece of standard documentation for ajax I could refer to?

    Thanks