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); } });
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
});
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});
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
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly