jQuery retrieving the data from an AJAX call into the global scope
Posted 27 July, 2009on:
- In: Tutorials
- Comments Off on jQuery retrieving the data from an AJAX call into the global scope
Another quick one. Reading around it seems to be an issue. You make an AJAX call within a function and you want the call to be synchronous so that you can use the data from the call in the function scope.
AJAX calls are obviously asynchronous. jQuery has a ‘async: false’ option in AJAX calls but it is ignored by most (maybe all?) browsers. Using this method you can force a synchronous request and retrieve that data.
var myVariable = $.ajax(
So .responseText retrieves the text value of the response from the AJAX call. And because we’re assigning to a variable we are forcing a synchronous request. You can now use that variable as you see fit.
This causes an issue when you are trying to retrieve a JSON object from an AJAX call into the function scope. The best way I’ve found so far is to retrieve the JSON as a string and use a jquery JSON plugin to convert it into an accessible object. Or you could just use the ‘eval’ method.