I’m trying to return a value from (transport) to the calling function, but can’t seem to get it to work:
function createXMLHttpRequest( w )
{
var urly = '/users/notes/' + w;
var options = {
method:'get'
, onSuccess: function( transport )
{
x = transport.responseText;
return x;
}
, onFailure: function( transport )
{
var response = transport.responseText;
alert( "FAILED "+ response );
}
};
new Ajax.Request( urly, options );
alert( x );
}
var ai = $( 'addItem' );
ai.onclick = function()
{
// -1 indicates new
addnote( -1, null );
}
x always alerts undefined. Unless I assign x to the Ajax.Request e.g. x=new Ajax.Request(urly,options). It then will alert [Object object]. How can I return the value of transport.responseText to the onclick function?
Your Request is not
asynchronous:false. So x is alerted before the request is completed andxis set totransport.responseText.You have to either set the request as synchronous, or alert x in the
onSuccessmethod.The return value from onSuccess is discarded by Ajax.Request. Don’t return anything.
Ajax is asynchronous by nature. You should query the server, then handle the response in a callback. So you should not try to use the server value in the onclick function, but rather in a separate callback (the onSuccess method).