Reputation: 451
I have an application that gets an authentication token in every service call's response and it is supposed to send the previous token as a parameter for the next call otherwise user will be unauthorized. And once the token is mismatched, all the other calls fail.
To make sure that the tokens are not mismatched, i have added loaders on my screen and i display them as soon as an ajax call is initiated and keep the loading overlay on screen until the response is not received otherwise the user could click on any other link which would result in another ajax call.
But still, i think the loader mechanism is prone to loopholes. Is there any way to check if any ajax call is in progress, then queue the new one and the queued one shall wait for the initiated ones response because it would need the token returned from its response as its new request parameter.
Upvotes: 1
Views: 1991
Reputation: 654
I just worked on a project where I did this. Let's say you've got your AJAX function, foo.ajax( url, callback )
.
You need a way to package all the details that would go out in an AJAX request. So you make a function foo.ajaxRequest(url)
and a list of requests, foo.requestList = []
and use them like this:
foo.ajaxRequest = function( url ) {
foo.requestList.push(this);
var callback = function( data ) {
if ( foo.requestList.length ) {
foo.requestList.shift().run( data );
}
}
this.run = function( dataFromPreviousAjax ) {
foo.ajax( url + "?key=" + dataFromPreviousAjax, callback );
}
if ( !foo.requestList.length ) {
foo.ajax( url, callback );
}
}
and any time you want to make some requests, you write
new foo.ajaxRequest("http://stackoverflow.com/pingback.php");
new foo.ajaxRequest("http://stackoverflow.com/pingback.php");
and now suppose the first request returns a key of 12345
, the second request will now run and call the url "http://stackoverflow.com/pingback.php?key=12345"
.
Obviously you'd want to do more stuff with the return value in the callback function inside foo.ajaxRequest
, but this should get you started.
Upvotes: 1