Passing variable outside ajax function
ajax, javascript, jquery
Solution
The jQuery 1.5+ way of resolving this is by using deferred objects:
var res;
var ajax = $.ajax({
type: 'POST',
dataType: 'jsonp',
url: ...
}).done(function(results) {
// you may safely use results here
res = results;
...
});
// you cannot safely use 'res' here, only in code
// invoked via a 'done' callback on the `$.ajax` promise
console.log(res); // undefined
It would be incorrect to attempt to copy `results` into some other variable in the outer scope unless you have ensured that no other code tries to access that variable until the AJAX call has completed.
Problem
Please help - I have the following code which returns the variable 'results' in an alert. I want to use this variable outside of the function, and cannot get a callback, or outside declaration to work successfully. I'm sure I'm being a muppet, so I apologise for this basic question..... ``` <script src='http://code.jquery.com/jquery-1.9.1.js'></script> <script> $(function () { $.ajax({ type: 'POST', dataType: 'jsonp', url: 'https://creator.zoho.com/api/json/my-company-culture/view/PageFeed_Report?scope=creatorapi&authtoken=d670dc68ac0f6d7ca389e7b206a25045', success: function (results) { var raw_result=JSON.stringify(results); alert(results); } }); }); </script> ```