JQuery - Storing ajax response into global variable

JqueryXmlAjaxResponse

Jquery Problem Overview


Im still somewhat of a newbie on jQuery and the ajax scene, but I have an $.ajax request performing a GET to retrieve some XML files (~6KB or less), however for the duration the user spends on that page that XML content should not / will not change (this design I cannot change, I also don't have access to change the XML file as I am reading it from somewhere else). Therefore I have a global variable that I store the response data into, and any subsequent look ups on the data are done on this variable so multiple requests don't need to be made.

Given the fact that the XML file can increase, Im not sure this is the best practice, and also coming from a java background my thoughts on global public variables are generally a no-no.

So the question I have is whether there might be a better way to do this, and a question on whether this causes any memory issues if the file expands out to some ridiculous file size?

I figure the data could be passed into a some getter/setter type functions inside the xml object, which would solve my global public variable problems, but still raises the question on whether I should store the response inside the object itself.

For example, what I currently do is:

// top of code
var xml;
// get the file
$.ajax({
  type: "GET",
  url: "test.xml",
  dataType: "xml",
  success : function(data) {
    xml = data;
  }
});
// at a later stage do something with the 'xml' object
var foo = $(xml).find('something').attr('somethingElse');

Jquery Solutions


Solution 1 - Jquery

Here is a function that does the job quite well. I could not get the Best Answer above to work.

jQuery.extend({
    getValues: function(url) {
        var result = null;
        $.ajax({
            url: url,
            type: 'get',
            dataType: 'xml',
            async: false,
            success: function(data) {
                result = data;
            }
        });
       return result;
    }
});

Then to access it, create the variable like so:

var results = $.getValues("url string");

Solution 2 - Jquery

There's no way around it except to store it. Memory paging should reduce potential issues there.

I would suggest instead of using a global variable called 'xml', do something more like this:

var dataStore = (function(){
    var xml;

    $.ajax({
      type: "GET",
      url: "test.xml",
      dataType: "xml",
      success : function(data) {
                    xml = data;
                }
    });

    return {getXml : function()
    {
        if (xml) return xml;
        // else show some error that it isn't loaded yet;
    }};
})();

then access it with:

$(dataStore.getXml()).find('something').attr('somethingElse');

Solution 3 - Jquery

This worked for me:

var jqxhr = $.ajax({
	type: 'POST',		
	url: "processMe.php",
	data: queryParams,
	dataType: 'html',
	context: document.body,
	global: false,
	async:false,
	success: function(data) {
		return data;
	}
}).responseText;

alert(jqxhr);
// or...
return jqxhr;

Important to note: global: false, async:false and finally responseText chained to the $.ajax request.

Solution 4 - Jquery

You don't have to do any of this. I ran into the same problem with my project. what you do is make a function call inside the on success callback to reset the global variable. As long as you got asynchronous javascript set to false it will work correctly. Here is my code. Hope it helps.

var exists;

//function to call inside ajax callback 
function set_exists(x){
    exists = x;
}

$.ajax({
    url: "check_entity_name.php",
    type: "POST",
    async: false, // set to false so order of operations is correct
    data: {entity_name : entity},
    success: function(data){
        if(data == true){
            set_exists(true);
        }
        else{
            set_exists(false);
        }
    }
});
if(exists == true){
    return true;
}
else{
    return false;
}

Hope this helps you .

Solution 5 - Jquery

You might find it easier storing the response values in a DOM element, as they are accessible globally:

<input type="hidden" id="your-hidden-control" value="replace-me" />

<script>
    $.getJSON( '/uri/', function( data ) {
        $('#your-hidden-control').val( data );
    } );
</script>

This has the advantage of not needing to set async to false. Clearly, whether this is appropriate depends on what you're trying to achieve.

Solution 6 - Jquery

your problem might not be related to any local or global scope for that matter just the server delay between the "success" function executing and the time you are trying to take out data from your variable.

chances are you are trying to print the contents of the variable before the ajax "success" function fires.

Solution 7 - Jquery

        function getJson(url) {
            return JSON.parse($.ajax({
                type: 'GET',
                url: url,
                dataType: 'json',
                global: false,
                async: false,
                success: function (data) {
                    return data;
                }
            }).responseText);
        }

        var myJsonObj = getJson('/api/current');

This works!!!

Solution 8 - Jquery

I really struggled with getting the results of jQuery ajax into my variables at the "document.ready" stage of events.

jQuery's ajax would load into my variables when a user triggered an "onchange" event of a select box after the page had already loaded, but the data would not feed the variables when the page first loaded.

I tried many, many, many different methods, but in the end, it was Charles Guilbert's method that worked best for me.

Hats off to Charles Guilbert! Using his answer, I am able to get data into my variables, even when my page first loads.

Here's an example of the working script:

	jQuery.extend
	(
		{
			getValues: function(url) 
			{
    			var result = null;
				$.ajax(
					{
						url: url,
						type: 'get',
						dataType: 'html',
						async: false,
						cache: false,
						success: function(data) 
						{
							result = data;
						}
					}
				);
			   return result;
			}
		}
	);

	// Option List 1, when "Cats" is selected elsewhere
	optList1_Cats += $.getValues("/MyData.aspx?iListNum=1&sVal=cats");
	
	// Option List 1, when "Dogs" is selected elsewhere
	optList1_Dogs += $.getValues("/MyData.aspx?iListNum=1&sVal=dogs");
	
	// Option List 2, when "Cats" is selected elsewhere
	optList2_Cats += $.getValues("/MyData.aspx?iListNum=2&sVal=cats");
	
	// Option List 2, when "Dogs" is selected elsewhere
	optList2_Dogs += $.getValues("/MyData.aspx?iListNum=2&sVal=dogs");
	

Solution 9 - Jquery

     function get(a){
            bodyContent = $.ajax({
                  url: "/rpc.php",
                  global: false,
                  type: "POST",
                  data: a,
                  dataType: "html",
                  async:false
               } 
            ).responseText;
            return bodyContent;

  }

Solution 10 - Jquery

Ran into this too. Lots of answers, yet, only one simple correct one which I'm going to provide. The key is to make your $.ajax call..sync!

$.ajax({  
    async: false, ...

Solution 11 - Jquery

I know the thread is old but i thought someone else might find this useful. According to the jquey.com

var bodyContent = $.ajax({
  url: "script.php",
  global: false,
  type: "POST",
  data: "name=value",
  dataType: "html",
  async:false,
  success: function(msg){
     alert(msg);
  }
}).responseText;

would help to get the result to a string directly. Note the .responseText; part.

Solution 12 - Jquery

IMO you can store this data in global variable. But it will be better to use some more unique name or use namespace:

MyCompany = {};

...
MyCompany.cachedData = data;

And also it's better to use json for these purposes, data in json format is usually much smaller than the same data in xml format.

Solution 13 - Jquery

I'd suggest that fetching large XML files from the server should be avoided: the variable "xml" should used like a cache, and not as the data store itself.

In most scenarios, it is possible to examine the cache and see if you need to make a request to the server to get the data that you want. This will make your app lighter and faster.

cheers, jrh.

Solution 14 - Jquery

.get responses are cached by default. Therefore you really need to do nothing to get the desired results.

Solution 15 - Jquery

Similar to previous answer:

<script type="text/javascript">

    var wait = false;

    $(function(){
        console.log('Loaded...');
        loadPost(5);
    });

    $(window).scroll(function(){
      if($(window).scrollTop() >= $(document).height() - $(window).height()-100){
        // Get last item
        var last = $('.post_id:last-of-type').val();
        loadPost(1,last);
      }
    });

    function loadPost(qty,offset){
      if(wait !== true){

        wait = true;

        var data = {
          items:qty,
          oset:offset
        }

        $.ajax({
            url:"api.php",
            type:"POST",
            dataType:"json",
            data:data,
            success:function(data){
              //var d = JSON.parse(data);
              console.log(data);
              $.each(data.content, function(index, value){
                $('#content').append('<input class="post_id" type="hidden" value="'+value.id+'">')
                $('#content').append('<h2>'+value.id+'</h2>');
                $('#content').append(value.content+'<hr>');
                $('#content').append('<h3>'+value.date+'</h3>');
              });
              wait = false;
            }
        });
      }
    }
</script>

Solution 16 - Jquery

Just use this. simple and effective:

var y;

function something(x){
return x;
}

$.get(bunch of codes, function (data){

y=something(data);
)}

//anywhere else
console.log(y);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDomView Question on Stackoverflow
Solution 1 - JqueryCharles GuilbertView Answer on Stackoverflow
Solution 2 - JqueryLuke SchaferView Answer on Stackoverflow
Solution 3 - JqueryPhil LoweView Answer on Stackoverflow
Solution 4 - JqueryDomView Answer on Stackoverflow
Solution 5 - JqueryAidan FitzpatrickView Answer on Stackoverflow
Solution 6 - JqueryvortexView Answer on Stackoverflow
Solution 7 - JqueryDarthVaderView Answer on Stackoverflow
Solution 8 - JqueryCityPickleView Answer on Stackoverflow
Solution 9 - JqueryEdmhsView Answer on Stackoverflow
Solution 10 - JquerystvnView Answer on Stackoverflow
Solution 11 - Jqueryuser759740View Answer on Stackoverflow
Solution 12 - JqueryzihotkiView Answer on Stackoverflow
Solution 13 - JqueryjrharshathView Answer on Stackoverflow
Solution 14 - JqueryredsquareView Answer on Stackoverflow
Solution 15 - JqueryKyle CootsView Answer on Stackoverflow
Solution 16 - JqueryRezaAhmadiView Answer on Stackoverflow