Look my code:
I am using Jamal framekwork.
Event: {
getEvents: function(){
var events;
$.ajax({
type: "POST",
url: anchor("Events/getEvents"),
success: function(data) {
if(data){
events = data;
console.log(events);
}
}
});
console.log(events);
return events;
}
}
The first Output is:
{"0":{"id":"1","title":"title","description":"comment"},"1":{"id":"2","title":"title2","description":"comment2"}}
The second Output:
Undefined
If var events is a Global, why cant I set the value inside the ajax function and get the value after?
Jamal is breaking something?
It’s because variable:
Is initialized in callback function – ajax call is asynchronous if you put:
right after ajax call variable isn’t assigned (it’ll be somtime – but you don’t know exacly when) – all logic need to be in callback.
Also you can make ajax call synchronous by setting:
async : falsethen your code should work as expected.