When I alert the returned value from the jsonServerResponse function, its value is undefined – despite JSON being returned from the process.php page.
function jsonServerResponse(operation, JSOoptionalData) {
JSOoptionalData = (typeof JSOoptionalData == "undefined") ? 'defaultValue' : JSOoptionalData
var jqxhr = $.ajax({
type: "POST",
url: "process.php",
data: "apicommand=" + JSOoptionalData,
success: function (json) {
return jQuery.parseJSON(json);
}
});
}
alert("Response as JS Object: "+jsonServerResponse("operation"));
I know that the problem is that the alert function made before the asynchronous request is complete, but I am unsure how to fix this problem. Any advice is really appreciated 🙂
Ok, I figured it out from a different post. The result can either be handled within the success callback, or you can add an argument that is itself a callback function and apply the result of the ajax request to the callback.
And gdoron, the line you have asked about makes the third argument optional. I hear it’s good practice, if you are going to pass some data onto the server (but you dont know how many variables) to add an optional argument and just pass a js object, convert this to a JSON string, and decode it server-side.
Peace! 🙂