JQuery - Storing ajax response into global variable
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");
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');
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.