How to make $.get() function synchronous in jQuery?
$.get also accepts parameter like this
$.get({
url: url,// mandatory
data: data,
success: success,
dataType: dataType,
async:false // to make it synchronous
});
Although already answered:
$.ajax({
method: 'GET',
async: false
});
I want to warn of you the following:
- Blocks javascript execution, and might thus lock the webpage (no buttons working etc etc, it looks like your page hangs during the ajax call)
- Using synchronous calls gives console warnings.
Javascript is build based on event-driven design. you could also fire an custom named event (with the data result in the event data) when the ajax/get call is complete and let the followup action listen to this event.
eg:
$(form).on('submit',function(){
var formEl = this;
$.get({...}).success(function(data){
var event = new Event('data-submitted');
event.data = data;
formEl.dispatchEvent(event);
})
});
$(form).on('data-submitted',function(event){
var data = event.data;
// you can handle the post ajax request event here.
});
add an object parameter
$.get({
url: 'your-url',
async:false
});