I have a $.post function inside of a loop. All it does it call a php function to validate an input. If the input validates, it returns “true” (which I tested and works). At this point I use a callback to do some processing and it is not working.
For example if i am looping over three items, the callback function processes the third item three times instead of each one.
Here is my relevant code:
for (step in steps) {
var step_name = steps[step];
// grab input value
var step_answer = escape($("#" + step_name).val());
if (step_answer != "") {
// check to see if answer validates
console.log(step_name) // THIS SHOWS CORRECT VALUES: 1, 2, and 3
$.post("utility.php", {
utility: "validateAnswer",
step: step_name,
answer: step_answer
},
function(data) {
// if validation suceeds..
if (data == "true") {
console.log(step_name); // THIS SHOWS WRONG VALUES: 3, 3, and 3
correct_steps.push(step_name);
}
});
}
}
Any ideas? Thanks.
This is a problem with the way javascript does closures. Basically, when you create a variable at the top level (like you are doing), it actually just creates window.step_name which is actually a global variable and therefore the value doesn’t get encapsulated in the callback.
However, if you create a variable inside a function, this does not happen. So try wrapping your code in a function and see if it works.
Simple way:
If that works you might want to consider putting your code in a named function for easier maintenance later.
Alternatively, you could just use jquery’s $.each: