Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use variable outside the success function from an ajax/jquery call

I have the following code

var test;

 $.ajax({
    type: "GET",
    url: "../views/person/controller.php?actor=person&action=checkAge",
    data: "age=" + value,
    success: function(msg){
        console.log(msg);
        test = msg; 
    },
});

Validate.fail(test);

Now the test var should give true of false like the console does say. But test var gives me undefined why?

like image 320
DownDown Avatar asked May 09 '11 11:05

DownDown


People also ask

How use jQuery variable outside function?

When you declare the variable inside function . It has its scope limited to that function only(In case one of your scenario). To access them everywhere outside function you need to declare it as global variable.

How do you call a variable outside a function in JavaScript?

To access a variable outside a function in JavaScript make your variable accessible from outside the function. First, declare it outside the function, then use it inside the function. You can't access variables declared inside a function from outside a function.


3 Answers

 var test; // <-- (1) This code runs first  
 $.ajax({  // <-- (2) Then this runs  
    type: "GET",
    url: "../views/person/controller.php?actor=person&action=checkAge",
    data: "age=" + value,
    success: function(msg){
        console.log(msg); //<-- (4) Finally this is run. IF your request is a success 
        test = msg; 
    },
 });
 Validate.fail(test); // <-- (3) This runs third  

Look at the order in which the code runs. Your variable is simply not available at that point because it's running when the code is triggered via the callback

like image 105
JohnP Avatar answered Oct 11 '22 20:10

JohnP


Probably because Validate.fail(test) occurs immediately after the asynchronous call. Remember it is ASYNCHRONOUS, meaning it executes parallel to javascript running on your page.

like image 27
maple_shaft Avatar answered Oct 11 '22 19:10

maple_shaft


var test;
 $.ajax({
    type: "GET",
    async: false,
    url: "../views/person/controller.php?actor=person&action=checkAge",
    data: "age=" + value,
    success: function(msg){
        console.log(msg);
        test = msg; 
    },
});
Validate.fail(test);

//Make your ajax function synchronous, set the json parameter "async: false", so javascript has to wait until test is assigned a value.

like image 29
Julio Cesar Lopez Ocampo Avatar answered Oct 11 '22 20:10

Julio Cesar Lopez Ocampo