What is the difference between async:false and async:true in jquery ajax?

In jquery ajax there is a parameter

$.ajax({async: true, ...});

What is the difference between setting the value to true and false?


Solution 1:

You set async to false, when you need that ajax request to be completed before the browser passes to other codes:

<script>
    // ...
    $.ajax(... async: false ...); // Hey browser! first complete this request, 
                                  // then go for other codes

    $.ajax(...); // Executed after the completion of the previous async:false request.
</script>

By default, the$.ajaxrequest in jQuery is set to asynchronous. The variable name is async and the value is set to true. This gave me a little confusion as well when first learning about it, so let’s go over it.

Synchronous ( async: false ) – Script stops and waits for the server to send back a reply before continuing. There are some situations where Synchronous Ajax is mandatory.

In standard Web applications, the interaction between the customer and the server is synchronous. This means that one has to happen after the other. If a customer clicks a link, the request is sent to the server, which then sends the results back.

Because of the danger of a request getting lost and hanging the browser, synchronous javascript isn’t recommended for anything outside of (onbefore)unload event handlers, but if you need to hear back from the server before you can allow the user to navigate away from the page, synchronous Javascript isn’t just your best option.

$.ajax({
         url: "file.php",
         type: "POST",
         async: false,
         success: function(data) {
                // .....
         }
      });

Asynchronous ( async: true ) – Where the script allows the page to continue to be processed and will handle the reply if and when it arrives. If anything goes wrong in the request and/or transfer of the file, your program still has the ability to recognize the problem and recover from it. Processing asynchronously avoids the delay while the retrieval from the server is taking place because your visitor can continue to interact with the web page and the requested information will be processed with the response updating the page as and when it arrives.

$.ajax({
         url: "file.php",
         type: "POST",
         async: true,
         success: function(data) {
                    // .....
         }
       });

Also take a look at this article

Asynchronous and Synchronous AJAX calls

Solution 2:

Setting it to false blocks the main thread (responsible for executing JavaScript, rendering the screen, etc) and waits for the XHR to complete.

This is almost always a terrible idea. Users don't like unresponsive UIs.