I'm trying to call this variable outside the function but I get undefined as a result. I understand without var the variable could be called in global scope but i get undefined. I also tried setting the var outside the function and calling it but no success also. Here's my simplified code thank you :)
function function1() {
$.getJSON('random.json')
.success(successfunction)
.error(failfunction);
function successfunction(data) {
testvar = (data.name);
}
function failfunction(error) {
console.log(error);
}
};
console.log(testvar);
$( document ).ajaxStop(function() {}
if you want global scope attach your variable to global object like window
function successfunction(data){
window.testvar = "var";
}
By that you will be sure that it becomes global .
However, you should note that successfunction
is a callback that will be running later on : it is running after timeout & only if the ajax call succeeded .