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?
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.
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.
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With