[jquery] JQuery - Storing ajax response into global variable

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

This question is related to jquery xml ajax response

The answer is


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


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.


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

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.


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, ...

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

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

  }

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>

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.


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.


        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!!!


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.


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

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.


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 .


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to xml

strange error in my Animation Drawable How do I POST XML data to a webservice with Postman? PHP XML Extension: Not installed How to add a Hint in spinner in XML Generating Request/Response XML from a WSDL Manifest Merger failed with multiple errors in Android Studio How to set menu to Toolbar in Android How to add colored border on cardview? Android: ScrollView vs NestedScrollView WARNING: Exception encountered during context initialization - cancelling refresh attempt

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to response

Returning JSON object as response in Spring Boot Guzzlehttp - How get the body of a response from Guzzle 6? Keep getting No 'Access-Control-Allow-Origin' error with XMLHttpRequest Express.js Response Timeout What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response) Return generated pdf using spring MVC Create HTTP post request and receive response using C# console application java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed C# Encoding a text string with line breaks Remove Server Response Header IIS7