PDA

View Full Version : How do you get a value out of a callback function during an ajax request?



BarryOg
7 Jul 2007, 2:39 PM
I have the following function for making ajax request against my php data layer:



function sendCall(dataToSend, domDump){


var retString;

var con = new Ext.data.Connection();
con.request({
url: 'http://www.liamolony.com/game/jsonInterface.php5',
params: {data: Ext.util.JSON.encode(dataToSend)},
method: 'post',
callback: function(opts,suss,resp) {
if(resp.responseText != ''){
alert(Ext.util.JSON.decode(resp.responseText));

if(domDump != ''){
Ext.get(domDump).dom.innerHTML = Ext.util.JSON.decode(resp.responseText);
}
}
}
}
);

return retString;

}


Is there a way to get resp.responseText out of the callback function without using a div in between? Or if its impossible how do I ensure that the div contents doesn't get shown?

evant
7 Jul 2007, 3:40 PM
What do you mean "without using a div," you're getting it without using a div right here:



alert(Ext.util.JSON.decode(resp.responseText));

BarryOg
8 Jul 2007, 3:56 AM
Sorry I wasn't very clear there, I'm using the value within the scope of the callback function when I use alert() but I'd like to be able to return the responseText from the sendCall() function.

I thought of another workaround which is calling another function from within the callback function which sets a global variable with the result but that's messy for what I want to do with my sendCall() function.

Wolfgang
8 Jul 2007, 11:39 PM
Sorry I wasn't very clear there, I'm using the value within the scope of the callback function when I use alert() but I'd like to be able to return the responseText from the sendCall() function.
That will not work, because the callback (and the corresponding XHR call) is asynchrones to your call of sendCall(). (That is one reason to setup callbacks).
In other words: sendCall() does not wait for the XHR request to complete or for the callback to be called. The callback is called when it gets the answer to the XHR request.



I thought of another workaround which is calling another function from within the callback function which sets a global variable with the result but that's messy for what I want to do with my sendCall() function.
You can set a global var or call a function from within you callback to set the response.text.
But i am sure it will not help you, as this can / will happen asynchrones to your call of the function sendCall().

So i suggest that you revisit the sw design. It is very likely that you can do what you want to do from within the callback function.

Regards

Wolfgang

BarryOg
9 Jul 2007, 5:41 AM
Thanks for the reply wolfgang, yes I had hoped to come up with a general function which I could use to perform all my transactions with the back end, but I hadn't been thinking about the fact that the calls where non-blocking.