How to make $ .get () function synchronous in jQuery?
I want to make the $ .get () method synchronous in my function. In ajax aysnc : false
helps me, now how do I do the same with$.get()
var ifsc_code = $('#ifsc-code').val();
var api_url = 'http://api.techm.co.in/api/v1/ifsc/'+ifsc_code;
$.get(api_url, function(data, status){
//console.log(data.status);
var status = data.status;
if (data.status == "success") {
$.each(data,function(key,value){
var address = value.BANK+", " + value.BRANCH+", " + value.ADDRESS ;
$('.bank-details').removeClass('no-ifsc').text(address);
});
var res = "true";
alert('inside checkIfsc true');
return res;
}
else if (data.status == "failure") {
$('.bank-details').addClass('no-ifsc').text(data.message);
var res = "false";
alert('inside checkIfsc false');
return res;
}
Or is there any other approach to do the same?
+3
source to share
3 answers
Although already answered:
$.ajax({
method: 'GET',
async: false
});
I want to warn you the following:
- Blocks javascript execution and thus blocks the web page (buttons don't work, etc etc, it looks like your page is hanging during ajax call)
- Using synchronous calls gives console warnings.
Javascript is built around event-driven design. you can also fire a custom named event (with the result of the data in the event data) when the ajax / get call completes and the subsequent activity listens for that 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.
});
+3
source to share