PDA

View Full Version : Return a value



Valentyn
14 Dec 2014, 11:48 PM
I use function.

function getUnical(id, type) {
//var data = {};
var res = false;
Ext.Ajax.request({
url: 'inc/ajax/staff_edit.php?v='+type,
method: 'POST',
params: {
id: id
},
success: function(response){
//console.log(response);
var obj = Ext.decode(response.responseText);
//console.log(obj);
if (obj.success == 'error')
{
var staff = obj.staff;
Ext.getCmp(type).focus();
//console.log(staff);
res = staff;
}
}
});

return res;
}
After the query it must return a value. But for some reason always returns false.Why? How to return the "staff" value?

aaugen
15 Dec 2014, 12:51 AM
Hi Valentyn,

Ajax request is an asynchronous method so you can't return res value in your function. When you want return "res" value in your fonction, the success method is not already triggered by the http code response so your res value is always return false.

According to Ext.Ajax.request (http://docs.sencha.com/extjs/4.2.3/#!/api/Ext.Ajax-method-request) documentation:

Ajax server requests are asynchronous, and this call will return before the response has been received. Process any returned data in a callback function

Valentyn
15 Dec 2014, 4:33 AM
Thank you for your help. Could you show an example.
I do like that :

function getUnical(id, type) {
//var data = {};
var res = false;
...,
callback: function(response, opt){
console.log(response.success);
res = true;

},
scope: this
});

return res;
}
, but nothing happens, returns false. Using version 4.0.7. Thank you.

Valentyn
22 Dec 2014, 11:25 PM
Solved the problem this way. Thank you for your help!

function getUnical(id, type) {
var res;
Ext.Ajax.request({
url: 'inc/ajax/staff_edit.php?v='+type,
...
async: false,
....
callback: function(options, success, response){
var obj = Ext.decode(response.responseText);
if(obj.success=='error'){
res = obj.staff;
}
else
res = false;
}
});
return res;
}