Continuing with JQuery – Storing ajax response into global variable
Accepted solution somehow does not work for me.
$(document).ready(function() {
var dataStore = (function(){
var xml;
$.ajax({
type: "GET",
url: "/?do=getcontentadm1n&category=homepage",
dataType: "json",
success : function(data) {
xml = data.html;
alert(xml); // WORKS
}
});
return {getXml : function()
{
if (xml) return xml;
}};
})();
var somevar = dataStore.getXml();
alert(somevar); // UNDEFINED
});
Is there other solution?
Thanks.
It’s empty because by the time
getXmlis called, the ajax request has not completed, remember ajax is asynchronous. One way to get around it is to force it to be synchronous:Responding to comment: