Reputation: 1934
I am developing an app in PHP and at some points the app has to make multiple AJAX POSTs (which each return a small amount of HTML). Each of these POSTs has to insert the returned HTML in a div. I have no problem doing that but the problem comes when I start all the AJAX POSTs at once (let's say I start 10), and I specify a separate div for each POST. Because they are all asyncronous and they all return at about exactly the same time all the HTML ends up in one div, instead of each separate div. I'll post some code to clarify. Here is a stripped down version of my 'apiCall' function:
xhr = $.ajax({
type: "POST",
url: "../api.php",
dataType: "json",
data: data,
success: function(data) {
obj.html(data.D['html']);
}
});
It's around the success function where the problem occurs. data.D['html'] contains the HTML from the POST but I think its getting overwritten by the next AJAX POST so thats why all I see is the AJAX POST that returns last being put into the div (this is part of a jQuery plugin I wrote, obj is the div that was passed in) I call it like this:
$("#container).apiCall({options...});
Can anyone offer a solution to make it so that when these AJAX POSTs return I can put the returned data from that particular POST into the correct div?
Upvotes: 1
Views: 924
Reputation: 33442
You are doing this several times and you always refer to the same obj. In the meantime, you are overwriting your obj.
By the time all the ajax functions are set up and the responses are starting to arrive (and the callback start to run), all the obj references point to the last value of obj.
Use a closure to preserve it in another variable (in this case, myObj):
xhr = (function(){
var myObj = obj;
return $.ajax({
type: "POST",
url: "../api.php",
dataType: "json",
data: data,
success: function(data) {
myObj.html(data.D['html']);
}
});
})();
Instead of assigning what $.ajax() returns directly to xhr, it creates an anonymous function and calls it inmediately: ( function(){ /* code */ } )()
That function "backups" obj into myObj (a variable local to the anonymous function), and then simply returns what $.ajax() returns.
I didn't test this code. Tell me if there is any error.
Upvotes: 3