Rather odd problem in that I cannot use the data variable (the information returned by the ajax call) anywhere but in the .ajax function itself.
I am sure this is an issue of scope, however it is one that is beyond me and would be grateful of any pointers.
$('img#test').live('click', function(e) {
e.preventDefault();
var test = getPreviewImage();
alert(test); // This just gives undefined
});
function getPreviewImage()
{
var output;
var img_bg = $('div#preview-1 img:nth-child(1)').prop('src');
var img_fg = $('div#preview-1 img:nth-child(2)').prop('src');
$.ajax({
url: "/blah.php?v=12345,
}).done(function (data) {
alert(data); // This gives the correct response
output = data; // This should take the data value but still be in scope for the return statement below
});
return output;
}
You can call another function using the
$.ajax
jQuery function. Try doing the following.This isn't really a problem of scope but of synchronicity.
When your
getPreviewImage
function returns, the ajax call hasn't yet be made (it's asynchronous and the execution flow doesn't wait for the request and response to be complete), sooutput
is still null.You can solve this by making a synchronous ajax call or by providing a callback to
getPreviewImage
instead of using its return value.To make a synchronous ajax call, pass
false
as theasync
parameter. See the doc.To use a callback, you can do this :
Using a synchronous call is easier (you just have to set a parameter to false) but the callback logic is generally preferable as it doesn't block your script and allows parallel requests.