I am working with jQuery and I need to handle the data gathered during an AJAX call outside of the AJAX object:
function getData(yt_url) {
$.ajax({
type: "GET",
url: yt_url,
dataType: "jsonp",
success: function(response) {
// Return response here //
},
error: function(request, status, error) {
alert(status);
}
});
}
I would like to call the function getData
and receive the response object in the AJAX success function.
I've tried adding some returns and then of course I realized it was an object.
AJAX is asynchronous, which basically means that it does not block the execution of the script (which is good, as your website does not freeze while things load).
return
ing a value like you're doing is synchronous, which is incompatible with AJAX.
One solution would be to pass a callback function into getData
that gets called when the AJAX request finishes:
function getData(yt_url, callback) {
$.ajax({
type: "GET",
url: yt_url,
dataType: "jsonp",
success: callback,
error: function(request, status, error) {
alert(status);
}
});
}
And then you could use it like this:
getData('http://www.example.com/', function(response) {
alert('The response was: ' + response);
});
You can try something like this - add a global variable that will store the result of the ajax call, for example
var ajaxResult = null;
set ajax's async property to false and then write something like this:
var ajaxResult = null;
function getData(yt_url){
$.ajax
({
type: "GET",
url: yt_url,
dataType:"jsonp",
async: false,
success: function(response){
ajaxResult = response;
},error:function (request, status, error)
});
}
getData(yt_url); // call the function to try to get the result if(ajaxResult != null){ // if we got some result during the ajax call
// do something with the result
}
Since AJAX is asynchronous, you should restructure your code to receive the data in a callback function. Whenever the request is finished, you then can continue with whatever you wanted to do with the data. An example:
$.ajax {
type: "GET",
url: url,
dataType:"jsonp",
success: success,
error: error
};
function success(data) {
// continue your work here.
}
function error(request, status, error) {
// handle any errors here.
}
I would not recommend using async: false
, since it freezes the browser until it finishes executing your request, while in general you might like it to remain responsive while it processes your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With