How to make Ajax request synchronous in jQuery?


Is there any way to make Ajax request Synchronous in jQuery/javascript?

I am trying to fetch a data from the server while loading the <div> data and depending on that data, i will fetch another query, which can be asynchronous but the first one should be synchronous as data will be parsed after the success of the call.

Code:

   $.ajax({
           url: "/Controller/Action",
           data: "sometext="+valueSelected,
           type: "GET",
               success: function (resp) {
                 if (resp == 1) {
                   //fetch new data calling ajax again
                 } else {
                   // don't fetch
                 }
               },
               error: function (e) {
                 console.log(e);
               }
         });

Asked by:- pika
3
: 6571 At:- 8/1/2017 12:33:45 PM
jQuery javascript ajax-synchronous







3 Answers
profileImage Answered by:- manish

jQuery ajax request can be made Synchronous using it's settings

async: false

which is true by default, setting async:false will make it synchronous

Note: Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.Synchronous requests may temporarily lock the browser, disabling any actions while the request is active

read more about it on jQuery.Ajax()

So, it should be like

 $.ajax({
        url: '/example',
        async: false
    });
2
At:- 8/1/2017 3:04:21 PM Updated at:- 12/24/2022 6:55:17 AM


profileImage Answered by:- vikas_jk

You can simply do something like this, Set ajax to synchronous before the ajax call, and then reset it after your ajax call:

$.ajaxSetup({async: false});

$ajax({ajax call....});

$.ajaxSetup({async: true});

 

1
At:- 8/1/2017 3:24:32 PM
This one is correct and useful, since it makes code more readable. 0
By : jon - at :- 12/24/2022 2:22:35 PM


profileImage Answered by:- bhanu

Although, above answers work perfectly for making ajax synchronous, but making async: false might bring issues for User experience and hand user browser.

So, if you still want to use synchronous but still don't block the browser, then you should use async/await and probably also some ajax that is based on promises like the new Fetch API

async function foo() {
  var res = await fetch(url)
  console.log(res.ok)
  var json = await res.json()
  console.log(json)
}

One more point to consider here is:

If you are doing cross-domain ajax synchronous call using "async:false" and jsonp, then both these attributes will be ignored.

$.ajax({
    url: "testserver.php",
    dataType: 'jsonp', // jsonp
    async: false //IGNORED!!
});

For making jsonp request, synchronous, it is better to use "function sequencer" library like Frame.js

1
At:- 9/16/2021 8:08:16 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use