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:
var myVariable;
$.ajax({
//stuff....
success:function(data) {
myVariable = data;
}
});
alert(myVariable); // at this point myVariable is undefined!!
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 of myVariable
.
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:
var myVariable;
$.ajax({
//stuff....
success:function(data) {
myVariable = data;
}
});
/*
* Do lots of stuff with the returned value
* of the myVariable variable
*
*/
you now need to write it like this:
var myVariable;
$.ajax({
//stuff....
success:function(data) {
myVariable = data;
/*
* Do lots of stuff with the returned value
* of the myVariable variable
*
*/
}
});
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.