I have a javascript that interacts with a database in the following way (refer to code below):
- Gets into a loop that runs through an array called fruits().
- For each fruit, the php script getFruitData.php is called with one fruit as argument (and then it uses that string to return data about that fruit from a MySQL database).
- Lists the data once returned. Have excluded that code as it's not where the problem is.
The problem: the 'num' for loop is acting fishy. In the ajax function call it uses the correct number (0, 1 and 2 respectively), so I'm sending the right fruits to the database and get the right info back. But inside the ajax 'success' function, 'num' is always 3 (the length of the fruits array). This is weird, as the returned results is displayed one by one when I run the code.
Anyone who knows what I'm doing wrong? Have also tried both while/for loops with a global num variable that I increment inside the loop, but it comes with the same result. It's impossible to get the loop value of 'num' into the ajax response function.
Technically I could of course pass the num value over to php and then return it, that would work, but there must be a more elegant way of doing this and I also want to know what I'm doing wrong. Suggestions?
<body>
<button id="display" value="try"> Goho!</button>
<script>
$(document).ready(function()
{
$("#display").click(function()
{
var fruits=["Apple","Orange","Banana"];
for(num=0; num<fruits.length;num++)
{
$.ajax(
{
type: 'POST',
url: 'getFruitData.php',
dataType: 'json',
// The variable here gets the correct num value (0, 1 or 2)
data: {variable:fruits[num]},
success: function( response )
{
var dbEntries = $.map(response, function(el) { return el });
// When printing 'response', the correct data is displayed.
window.alert (response);
// num is always 3 here! (length of the array)
window.alert(num);
}
});
}
});
});
</script>
</body>