Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store ajax data into a global variable

Tags:

jquery

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.

like image 671
Alex G Avatar asked Feb 07 '12 04:02

Alex G


2 Answers

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
});
like image 51
driangle Avatar answered Oct 15 '22 03:10

driangle


The ajax call is async. It probably hasnt finished running when you call:

var somevar = dataStore.getXml();
like image 42
ozczecho Avatar answered Oct 15 '22 02:10

ozczecho