How to make a synchronized ajax call
Introduction
If we use the jquery ajax api, it an asynchronism by default, most of time this is what we need, but in some special case we will want to make a synchronized ajax call.
Using the code
For make a synchronized ajax call, we can use ‘async: false‘ setting, it will disable async for handle the return value. For example:
var jqXHR = $.ajax({ url: 'http://www.abc.com/checkExists', type: 'POST', async: false, //disable async for handle the return value data: data });
and we can check the return value with ‘jqXHR.responseJSON‘, so we can create a function for that:
function syncAjax(url, data){ var jqXHR = $.ajax({ url: url, type: 'POST', async: false, data: data }); return jqXHR.responseJSON }
use the function as below:
var result = syncAjax('http://www.abc.com/checkExists',{ orderNo: '00001' }); if(result.isExist){ //this is the server side value for return //to do... }
that’s all, you can do everything what you need now 🙂
41,873 total views, 20 views today
Leave a Reply