I have 2 functions with ajax call. How can i use the variables in function2 that return in function1.
function func1 (){
$.ajax({
url:"",
dataType: 'json',
success: function(data){
var foo
}
});
//How can i use var foo in func2(foo)?
//i try .done(func2(foo)); but it returns foo is not define
}
function func2 (param){
$.ajax({
url:"",
dataType: 'json',
success: function(data){
}
});
}
You must set the variable
fooglobally, andasynctofalse, so the browser can wait to execute func1 before executing func2:You could also have done it without initializing the var, as said by Ozerich; but is a good practice to have all your variables initialized.
Remember that if you initialize again the variable inside the success callback (using
var fooagain) you will be referring to a new variable named foo instead of the globally one.You can know more about javascript variable scopes searching the web.. https://stackoverflow.com/a/500459/407456
btw, you should consider executing your func2 inside the
successcallback of the func1.