0

I need to get a variable from inside the GET request and use it inside the function. It's not working. Here is my code:

function chooseChosenOne() {

         $.get("generate.php", function(data) {
           var chosenOne = targetLocation[data.randomNumber];
         }, "json");

         alert(chosenOne);

       }

How can I fix this? How can I use the variable "chosenOne" outside of that function in the GET request?

Fred
  • 1
  • 2

3 Answers3

0

You have to use the jQuery plugin getURLParam

value = $.getURLParam("paramName");
Igor
  • 2,619
  • 6
  • 24
  • 36
0

At the time you call alert(chosenOne);, the Ajax callback is not executed yet. Ajax is asynchronous. The function chooseChosenOne will not wait until the Ajax called finished, it will return immediately.

You can only work the return value in the callback:

function chooseChosenOne() {
     $.get("generate.php", function(data) {
         var chosenOne = targetLocation[data.randomNumber];
         alert(chosenOne); 
     }, "json");
}

So what you have to do is to make your function accept a callback which gets called as soon as the value is available:

function chooseChosenOne(callback) {
     $.get("generate.php", function(data) {
         callback(targetLocation[data.randomNumber]);
     }, "json");
}

chooseChosenOne(function(theOne) {
   // now do stuff with theOne here
});

See also:

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

'chosenOne' only exists inside your callback function, and your code will hit the alert() before the callback has even run...

function chooseChosenOne() {           
     $.get("generate.php", function(data) {            
                doSomethingWithChosenOne(targetLocation[data.randomNumber]);
               }, "json");
} 

function doSomethingWithChosenOne(v){
   alert(v);
}
Tim Williams
  • 154,628
  • 8
  • 97
  • 125