Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery 1.8, async: false with jqXHR ($.Deferred) is deprecated

Tags:

jquery

I have been having a few issues with ajax error function getting called while the script is taking a while to load. But I was able to fix it by adding async: false.

E.g:

$.ajax({
    type: 'POST',
    url: REQUEST_URL,
    async: false,
    data: {
        'id': id
    },
    dataType: 'json',
    success: function(output) { 
        // success
    },
    error: function() {
        alert('Error, please refresh the page');
    }
});

When reading the docs it says:

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the complete/success/error callbacks.

Q) What does the last part mean about jqXHR ($.Deferred)? Does this effect my script?

like image 683
John Magnolia Avatar asked Nov 30 '12 08:11

John Magnolia


People also ask

Is async false deprecated?

As of jQuery 1.8, the use of async: false with jqXHR ( $.Deferred ) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() .

Why Synchronous XMLHttpRequest async false is not recommended?

Synchronous XMLHttpRequest (async = false) is not recommended because the JavaScript will stop executing until the server response is ready. If the server is busy or slow, the application will hang or stop.


1 Answers

It does not affect your script.

It means that, when performing synchronous AJAX requests, one should not use the deferred API exposed by the object returned by $.ajax() (like done() or fail() for instance), but rely on the complete and error handlers instead.

In other words, your code already uses the right pattern. You would have to modify it if it used deferred operations like:

// Do not write this code.
$.ajax({
    type: 'POST',
    url: REQUEST_URL,
    async: false,           // <-- Synchronous request.
    data: {
        'id': id
    },
    dataType: 'json'
}).done(function(output) {  // <-- Use of deferred method.
    // success
}).fail(function() {        // <-- There also.
    alert('Error, please refresh the page');
});
like image 119
Frédéric Hamidi Avatar answered Oct 11 '22 13:10

Frédéric Hamidi