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 getXml
is called, the ajax request has not completed, remember ajax is asynchronous. One way to get around it is to force it to be synchronous:
$.ajax({
async: false,
type: "GET",
url: "/?do=getcontentadm1n&category=homepage",
dataType: "json",
success : function(data) {
xml = data.html;
alert(xml); // WORKS
}
});
Responding to comment:
I want perform AJAX onclick, then store data.html for other mouse events
var dataStore = (function(){
var html;
function load(){
$.ajax({
async: false,
type: "GET",
url: "/?do=getcontentadm1n&category=homepage",
dataType: "json",
success : function(data) { html = data.html; }
});
}
return {
load : function() {
if(html) return;
load();
},
getHtml: function(){
if(!html) load();
return html;
}
}
})();
$(element1).click(function(){
dataStore.load();
});
$(element2).click(function(){
var html = dataStore.getHtml();
// use html
});
The ajax call is async. It probably hasnt finished running when you call:
var somevar = dataStore.getXml();
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