JQuery - Storing ajax response into global variable
Solution 1
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 2
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 3
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
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
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.
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Admin
Updated on April 24, 2020Comments
-
Admin about 4 years
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');
-
zihotki about 15 yearsWhen you are using a lot of global vars this is bad, but when you use them carefully this helps a lot. JQuery uses global vars ( $ and jQuery at least), ExtJS uses global vars too.
-
Rooster almost 12 yearsactually just adding the 'async : false' can solve a lot of the problems you will encounter with this.
-
stvn over 11 yearsthanks for the downgrade but hey, I came here looking for a solution that didn't have a blocking operation in it's body and for other people who may stumble on this question, my solution might be the answer!
-
Andrew Larsson over 11 yearsEveryone is necroposting on this question, so I might as well do it too. As of jQuery 1.8,
async: false
is deprecated, and there is always a better way to handle your code than to sync your requests. -
Armen Markossyan over 11 yearsand can create a lot of problems such as freezing a browser for several seconds :)
-
Aditzu over 10 yearsgod like answer for me :D
-
skozz over 10 years> [ALERT] This answer doesn't works. Read
rfc1484
's answer below. -
Maciek Semik about 10 yearsThis works pretty good! JUST 1 thing, if(data == true) needs to be changed. It might just be empty.
-
Maciek Semik about 10 yearsasync:false will create havoc! If you have a beforeSend with a loading gif or something, async will make it very ugly
-
Maciek Semik about 10 yearsasync is causing alot of issues. What can solve the async problem?
-
Luke Schafer about 10 yearsProbably because of the missed $() is all.
-
IberoMedia about 10 yearsI was trying to recreate nodes from the response ajax returned. My script would work whenever I used existing nodes, but did not work when trying to recreate the objects structured from ajax response. This solution worked for me. I won't explore right now, but I suspect the async setting made the difference.
-
sixty4bit over 9 yearsThis is the answer!! Thanks so much
-
sixty4bit over 9 yearsBTW Can you explain this? Why can't I just declare a global variable in the Ajax success handler?
-
RN Kushwaha almost 9 yearsThis one gives warning in chrome console like
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.
-
Luke Schafer over 8 yearscame back by this, years later, by happenstance. Please DO NOT use async:false, for reasons the internet can explain better than my 500 character limit here.
-
King almost 8 yearsThis worked for me like a charm. I have been struggling with storing ajax response into global variable for long time dammit
-
user1794918 over 7 yearsThis worked excellent for my project. All I used was the function call. Didn't need the true false stuff
-
John R Perry almost 7 yearsI agree with @skozz, it doesn't work. It returns undefined. The only way around this seems to be to make
async
false
. -
Zypps987 almost 7 years@ArmenMarkossyan What would be a better alternative to this? And why would it cause a lot of problems?
-
Armen Markossyan almost 7 years@Zypps987 The better alternative is to avoid such global variables and build a proper asynchronous architecture. Async programming is different from traditional ways, so it has a certain learning curve and it's impossible to explain in detail in a single comment.
async: false
makes the whole thread (tab) freeze while it finishes the call. Just try to make 10 consecutive calls in a single function an see what happens. Especially if these calls take some time (and they will always do). -
Anthony over 6 yearsSo simple! It worked for me, though instead of setting an input's value I used jQuery's .data() method to store JSON.
-
Robert almost 3 yearsLogical solution for some application it is really clean. Suggestion: in case of cancelled operations, it is better to reset the
value
ofyour-hidden-control