This is supposed to return a JSON object containing a list of picture filenames. The commented alert shows the correct data, but alert(getPicsInFolder("testfolder"));
shows "error"
.
function getPicsInFolder(folder) {
return_data = "error";
$.get("getpics.php?folder=" + folder, function (data) {
data = jQuery.parseJSON(data);
$.each(data, function (index, value) {
data[index] = "folders/" + folder + "/" + value;
});
//alert(data); // This alert shows the correct data, but that's hardly helpful
return_data = data;
});
return return_data;
}
What am I doing wrong?
You can't return "true" until the ajax requests has not finished because it's asynchron as you mentioned. So the function is leaved before the ajax request has finished.
You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this: promise. success(function (data) { alert(data); });
The $.ajax() function returns the XMLHttpRequest object that it creates. Normally jQuery handles the creation of this object internally, but a custom function for manufacturing one can be specified using the xhr option.
You are calling the asynchronous $.get()
method, where its callback function will be called after your getPicsInFolder()
function returns. Follow the comments in the example below:
function getPicsInFolder(folder) {
return_data = "error";
// Since the $.get() method is using the asynchronous XMLHttpRequest, it
// will not block execution, and will return immediately after it is called,
// without waiting for the server to respond.
$.get("getpics.php", function (data) {
// The code here will be executed only when the server returns
// a response to the "getpics.php" request. This may happen several
// milliseconds after $.get() is called.
return_data = data;
});
// This part will be reached before the server responds to the asynchronous
// request above. Therefore the getPicsInFolder() function returns "error".
return return_data;
}
You should consider refactoring your code in such a way that the logic to handle the JSON object is in the $.get()
callback. Example:
$.get("getpics.php?folder=test", function (data) {
// Handle your JSON data in here, or call a helper function that
// can handle it:
handleMyJSON(data); // your helper function
});
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