Alex G Alex G - 6 months ago 80
jQuery Question

Store ajax data into a global variable

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.

Answer

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
});