JQuery - Storing ajax response into global variable
Solution 1:
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:
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:
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 .