by Admin
21. July 2009 11:32
Download Sample Project
In last post, Using jQuery to send AJAX requests, i discussed some
basic concepts about how you can use simple .getJSON function to send AJAX requests using jQuery. For discussion of this post, I have added one more AJAX request into the mix. Now I want to another AJAX request to different target. But I want to make sure that second requests is only sent after first one is complete.
There is an async option that you can in jQuery. You can set this option to false to turn your AJAX request into a synchronous request. What this means is that your request is waiting till it completes. If you use this option you can write some code like below.
$(function(){
.getJSON("url1", "", callback1);
.getJSON("url2", "", callback2);
});
There are few issues with this approach. First, your first request will wait till timeout if there is any issue in network. So now your page is waiting as well to render. Second if your second request depends on completion or success of first one, then you do not have control. Second request will be sent no matter what. So setting async flag in general is not something you want to do. More elegent and very simple solution is to make second request in callback function of first request. This way your two calls are serialized now and you still enjoy benefits of async requests. In the sample project for clock synchronization, I have the following code snippet that demonstrates this method of ensuring that second request does not get fired before first one finishes.
function getServerTime() {
cTime = firstRequest ? -1 : curTime.getTime();
$.getJSON(clockServiceUrl, { clientTime: cTime, requestKey: respKey }, gotServerTime);
}
function getSiteUpdates() {
cTime = firstRequest ? -1 : curTime.getTime();
$.getJSON(siteUpdatesServiceUrl, { clientTime: cTime, requestKey: respKey }, gotSiteUpdates);
}
function gotSiteUpdates(data) {
if (data.MessageCount > 0) {
elUpdatesPanel.append('' + data.MessageCount + ' updates ' + '
');
}
}
function gotServerTime(data) {
firstRequest = false;
latency = data.Latency;
curTime = new Date(parseInt(data.ServerTime));
if (!clockTicking) createClockTimer();
createServiceTimer(defaultServiceTimer);
getSiteUpdates();
}