Can't Use Returned Data In .ajax Method Of Jquery Anywhere But The Function Itself
Solution 1:
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), so output
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 the async
parameter. See the doc.
To use a callback, you can do this :
$('img#test').live('click', function(e) {
e.preventDefault();
getPreviewImage(function(test){
// use test
});
});
functiongetPreviewImage(callback) {
$.ajax({
url: "/blah.php?v=12345",...
}).done(function (data) {
callback(data);
});
}
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.
Solution 2:
You can call another function using the $.ajax
jQuery function. Try doing the following.
functiongetPreviewImage()
{
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(someotherFunction)
});
}
function someotherFunction(data) {
return data;
}
Post a Comment for "Can't Use Returned Data In .ajax Method Of Jquery Anywhere But The Function Itself"