Friday, May 18, 2007

Passing additional arguments to YUI asyncrequest

When using YUI's asyncrequest command (YAHOO.util.Connect.asyncRequest), you need to pass a callback with "success" and "failure" functions. Success is where you put code that executes if the request is successfull and failure is where you put code in case the request failed.


var callback =
{
success: function(o) {/*success handler code*/},
failure: function(o) {/*failure handler code*/},
argument: [argument1, argument2, argument3]
}
YAHOO.util.Connect.asyncRequest('GET', "http://mywebsite.com", callback, null);



When making an ajax request, sometimes you want to be able to manipulate or access variables that are outside the scope of the success or fail function. Here's where the "argument" parameter of the callback comes in.

I discovered that I can literally pass anything I want as an argument. For example, after a successful request, I may want to read additional javascript variables to do further processing. I can even pass a javascript object.

In the snippet below, the argument is appended into "o" the object that is passed into the success and fail functions. To access your argument from either the success or failure functions, you need to use o.argument.argument_name.



var myvar = "this is a variable";
var callback =
{ success: function(o) {
/*success handler code*/
alert(o.argument.extvar);
},failure: function(o) {
/*failure handler code*/
alert(o.argument.extvar);
},argument: { extvar: myvar}
}
YAHOO.util.Connect.asyncRequest('GET', "http://mywebsite.com", callback, null);