I have a simple page here to demonstrate the issue that I am seeing.
I am defining a multidimensional array, populating it outside my functions. When I use ajax to send back some data to pupulate the array with the code seems to be adding the data to a temporary array.
When I try to access the array in my function once all ajax has been returned, I am only able to access the last row populate. All other rows return empty strings.
Code:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<div id=result>
</div>
<textarea id="the_code"></textarea>
<script language=javascript>
var images = [[0,"/upload/cut/1339722764_0_0.png", ""],[1,"/upload/cut/1339722764_0_1.png", ""]];
var numOfImages=1;
var recievedImages=0;
var num_row=1;
var num_col=2;
var x=0;
function recieveCode(codeid,emcode)
{
recievedImages=recievedImages+1;
images[codeid][2]=emcode;
$('#result').html('Generating: ' + Math.round(((recievedImages/numOfImages) * 100)) + '%');
if (recievedImages == numOfImages)
{
var i = 0;
var j = 0;
var imageID = "";
for(i = 0; i < num_row ; i++)
{
for(j = 0; j < num_col; j++)
{
if (j < num_col - 1)
{
imageID = imageID + "[[" + images[ (i*num_col) + j][2] + "]] ";
}
else
{
imageID = imageID + "[[" + images[(i*num_col) + j][2] + "]]\n";
}
}
}
$('#the_code').val(imageID);
}
}
for (x=0;x<numOfImages;x++)
{
$.ajax(
{
type: "POST",
data: {album : '223427061111247',image: images[x][1],auth: 'AAAB0ghwtqi0BAFI6xrLYurkQZBT2KWaiKUL3Jxbof3B5xdCIjZBpoImF0Q2ZAaqBC9ofzSPhGoCejyVaYNwIjC44Bay8gIR9Nj38KtGIxyhhgybbIOI' },
url: 'upload_emoticode.php',
success:function(msg){ recieveCode(images[x][0],msg); }
}
);
}
</script>
</body>
The problem is that your call to ajax is asynchronous so by the time
recieveCodeis called,xis always equal tonumOfImages. You can fix this by wrapping the call to ajax in an a self calling function that encapsulates each image in a closure like this: