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).
returning a value like you’re doing is synchronous, which is incompatible with AJAX.One solution would be to pass a callback function into
getDatathat gets called when the AJAX request finishes:And then you could use it like this: