I’m trying to change the value of a variable in a closure:
var myVariable;
$.ajax({
//stuff....
success:function(data) {
myVariable = data;
}
});
This does not work because myVariable is not visible to the closure. How do I change this code so that the value of myVariable changes?
Contrary to your belief, your code works. But seeing what you’re trying to do and reading between the lines I’m guessing you’re trying to do this:
If so, you need to learn about asynchronous functions.
Basically, the
$.ajax()function returns before actually submitting the ajax request. It will do the ajax request later when the browser is not busy executing javascript. Which means that the assignment will not have happened yet when you try to alert the value ofmyVariable.Read my response here for more detail: JS global variable not being set on first iteration
The only good solution is to change the way you think about coding. (There is an arguably bad solution that involves turning the ajax call to synchronous but lets not get in to that, you can google it if you want or read the manual). Instead of doing this:
you now need to write it like this:
Basically moving any and all code that you would have written after the ajax call into the success callback. This takes getting used to (judging from how many variants of this question exist on the internet). But once you’re used to it it becomes second nature.
There is a name for this style of programming. It is variously known as: “event driven programming” or “continuation-passing style” or “evented programming”. You can google the various terms if you want to know more.