Brent Kearney

Posted on: April 2nd, 2006 @ 20:03

Using dojo.io.bind() for XMLHttpRequest()

Since the introduction was so verbose in Part 1, I’ll just skip it in Part 2 :). This time, I’ll look at what is probably the most popular function from the Dojo I/O class, bind(). The bind() function is used to connect to external scripts or websites using XMLHttpRequest() in JavaScript. It really simplifies the whole process.

Dojo

Here’s the basics:


var myUrl = 'myscript.php?var1=foo&var2=bar';

dojo.io.bind(
	url: myUrl,
	type: "text/plain",
	error: errorFunction,
	load: resultFunction
);

function errorFunction(type, errorObject) {
	alert("Error! We got: " + type + ", and, " + errorObject);
}

function resultFunction(type, data, event) {
	alert("Success!  We got: " + data + " back from the server.");
}

The things to note about the above:

* myUrl can be anything; typically a php script, local or remote (http://somehost.com/somescript.php?myvars…). I put the variables and their values in the URI, as is typical in XMLHttpRequest() usage.

* By default, bind() uses the GET method to send the URL-encoded data, but you can change it to the POST method by invoking the method named “method”:
method: "POST",

* function parameters in the error: and load: methods are passed implicitly, as opposed to:

load: resultFunction( param1, param2, param3 ) // doesn't work

* errorFunction and resultFunction could be anonymous javascript functions, and judging by the Dojo documentation, that is the norm. For example:


dojo.io.bind(
	url: myUrl,
	type: "text/plain",
	error: function(foo, bar) {
                 alert("Error! " + foo + " and, " + bar);
              },
	load: function(type, data, event) {
                alert("Success! Script returned: " + data);
              }
});

* the parameters returned by the error: method are “type”, which is always “error”, and “errorObject”. From the manual, “The errorObject is transport specific, but should provide details about the type and details of the bind failure.” I haven’t played around too much with the error method.

* there are many more methods that could be used to tweak how dojo.io.bind() works. See the API manual for a list of them all.

That’s it, until Part 3!

Add comment