I’ve created an AJAX request in a function. However, I am not sure how to return the JSON result – can anyone show me how?
function getData(arg1, arg2, arg3){
Ext.Ajax.request({
url: 'getData.php',
params: {
arg1: arg1,
arg2: arg2,
arg3: arg3
},
method: 'POST',
success: function(response, opts) {
var jsonData = Ext.util.JSON.decode(response.responseText);
console.log(jsonData); <-- Can see the result here!
},
failure: function(response, opts) {
console.log('server-side failure with status code ' + response.status);
}
});
return /jsonData/ <-- Here is the value I want?!
}
The reason your
jsonDatawon’t get any information if you use it in yourgetDatafunctions is – when the success callback returns (remember, the request is asynchronous) – thegetDatascope is already exited.What you can and should do is define a handler function:
then define your
getDatalike so:Of course, you can do the same with your error handling:
Update
there is no way for you to do something like that (where
resultwill get the server response):reliably and still call an AJAX request. If you think about it – had the above been possible it would essentially become a synchronous request.
The two ways to do your calculations upon
jsonDatathat contains server response are:1) Do it in
handleSuccessfunction and adjust the rest of your code accordingly (as a side not – you can pass the handler functions as parameters toExt.Ajaxinoptions.callbackand )2) Make your server request synchronous (not advisable) by usual means