Remote

The Remote section of Mootools help you manage data and assets that are not on the page. These include Ajax, Json, Cookies, and Assets (such as images, css, and javascript).

Ajax.js

Here is the documentation for Ajax.js.

The Ajax class includes a lot of functionality wrapped around the XHR class. The XHR class, which we'll see later in the tutorial, is in turn a rather simple wrapper for the XMLHttpRequest object.

Basic syntax:

new Ajax(url, options);

With a bunch of options:

new Ajax('http://example.com/some/url.html', {
	method: 'post',
	//if method is post, you can write parameters here.  
	//Can be a querystring, an object or a Form element.
	data: $('myForm'),
	onComplete: handleMyAjax.bind(this),
	//onStateChange is an XHR option, but Ajax inherits from it
	//so we can use it
	onStateChange: myStateChecker.bindAsEventListner(this),
	//$(element) to insert the response text of the XHR into, upon completion of the request.
	update: $('returnMsg'),
	//Execute scripts in the response text onComplete.
	evalScripts: true
}).request();

Note: Mootools 1.1 changed the name of the "postBody" option to "data". "postBody" is deprecated, but may not be around in Mootools 1.2.

Here's an actual working Ajax request you can execute:

This is a div that we'll insert our ajax response into.

new Ajax('/Ajax.Request.Example.html', {
	method: 'get',
	update: 'ajaxExample',
	evalScripts: true,
	onComplete: function(){console.log('ajax complete!')}
}).request();
execute this code

Note that you can keep the ajax object around:

var myAjax = new Ajax(...);

Also note that creating an instance of the class doesn't actually fire the request; you need to call the method .request() to do that.

Object.toQueryString()

Converts an object to a query string:

Object.toQueryString({apple: "red", lemon: "yellow"}); //returns "apple=red&lemon=yellow"
execute this code

Element.send

Sends a form with an ajax post request.

<form id="myForm" action="submit.php">
	<input name="name" value="bob">
	<input name="zipCode" value="90210">
</form>
<script>
$('myForm').send({onComplete: handleMyResponse})
</script>

Assets.js

Assets.js provides on-the-fly loading of images, css, and javascript files. Here is the documentation for Assets.js.

Assets.javascript

Returns a new script tag with the source and (optional) properties you specify. *Note* that it inserts the tag into the DOM (in the head) for you.

new Asset.javascript('/scripts/myScript.js', {id: 'myScript'})
//returns element: <script src="/scripts/myScript.js" id="myScript"></script>

Assets.css

Pretty much the same concept for css as for javascript. *Note* that it inserts the tag into the DOM (in the head) for you.

new Asset.css('/css/myStyle.css', {id: 'myStyle', title: 'myStyle'});
//returns element: <link id="myStyle" rel="stylesheet" media="screen" type="text/css" href="/css/myStyle.css" title="myStyle">

Assets.image

Assets.image is very similar to Asset.css or .javascript, but its goal is to preload the image, while returning an image HTML element.

new Asset.image('/images/myImage.png', {id: 'myImage', title: 'myImage', onload: myFunction});
//returns element <img id="myImage" src="/images/myImage.png" onload="myFunction()" title="myImage">

Note that this doesn't actually do anything with the returned element, you'll need to use Element.injectBefore/injectAfter/injectInside/adopt/etc to put it somewhere:

new Asset.image('http://clientside.cnet.com/wp-content/themes/clientsidev2/art/logo.gif', {id: 'logoAsset', title: 'logo example'}).injectInside('logoExample');
execute this code

Asset.images

Preloads an array of images (as strings) and returns an array of img elements; does not inject them to the page.

var imgs = new Asset.images([urlOne, urlTwo, urlThree]);
imgs.each(function(img){img.injectInside(document.body)});

Cookie.js

Here is the documentation for Cookie.js.

The Cookie Object, does pretty much what you'd expect. It has three functions:

//let's store "example" as "some value" for 10 days
Cookie.set("example", "some value", {duration: 10});

You can set three (optional) options in the 3rd argument:

Cookie.set("example", "some value", {
	duration: 10, //ten days
	path: "/some/path", //now my cookie is available to
	//only content in this path
	domain: "example.com", //now my cookie is available to any
	//subdomains of example.com,
	secure: true //stored cookie information 
	//can be accessed only from a secure environment
});
//let's get it now
Cookie.get("example"); // -> "some value"
Cookie.remove("example"); //delete the cookie

Json.js

If you aren't familiar with Json, then you best read up. Here's the documentation for Json.js.

Json.toString

the .toString() method of the Json object will convert an object to a JSON string that can be evaluated back into the object.

Json.toString({apple: 'red', lemon: 'yellow'});
//returns: '{"apple":"red","lemon":"yellow"}'

Json.evaluate

Json.evaluate('{"apple":"red","lemon":"yellow"}');
//returns the object again: {apple: 'red', lemon: 'yellow'}
execute this code

Mootools 1.1 adds a second argument for Json.evaluate to first check that the response is valid Json. This security method ensures that you don't evaluate malicious code:

Json.evaluate('{"apple":"red","lemon":"yellow"}', true);
//returns the object again: {apple: 'red', lemon: 'yellow'}
execute this code
Json.evaluate("alert('you just got haxored!')", true);
//returns null
execute this code

Json.Remote.js

Here is the documentation for Json.Remote.js.

Json.Remote is a wrapper class for XHR to handle automated sending and receiving of Javascript Objects in Json Format.

Basic Syntax:

var jSonRequest = new Json.Remote(url, options)

I can't really demonstrate what this does in this tutorial, but here's an example of what you might do with it:

var jSonRequest = new Json.Remote(http://site.com/tellMeAge.php, onComplete: function(person){
	alert(person.age); //is 25 years
	alert(person.height); //is 170 cm
	alert(person.weight); //is 120 kg
}).send({'name': 'John', 'lastName': 'Doe'});

In the example above, we send "John Doe" to our tellMeAge.php which presumably looks up some information about that person and returns it in a Json format that looks something like:

{
	age: "25 years",
	height: "170 cm",
	weight: "120 kg",
	name: "John",
	lastName: "Doe"
}

Note that the Json.Request object has a .send method that takes a javascript object.

XHR.js

Here is the documentation for XHR.js.

The XHR class is a relatively simple wrapper for the XMLHttpRequest object (the heart of Ajax functionality). Most of the time you'll use the Ajax class (or the Json.Remote class), but the XHR has some useful tidbits that are worth knowing about.

The Json.Remote object is actually a great example of how to use XHR. Json.Remote really only concerns itself with the Json part (the whole class is only about a dozen lines), and relies on the functionality of the XHR class to do all the Remote parts.

XHR also provides you access to the basics of the Ajax functionality in Mootools, which means you can use .implement to change it. This is useful if you need to change the way Ajax requests work in your environment; one change will effect all the Ajax requests made in your code.

For instance, let's say that in your environment you want to define "failure" for an Ajax request not as a server response as is typically the case (by default, XHR defined success as a server response code >= 200 and < 300, and failure is anything else), but instead you want to define failure as some custom response, or you want to evaluate the response even if the server says it's a 200 response code.

Let's say your application returns Json values to you and if there's a problem, it returns:

{
	error: "Something went wrong!"
}

And you want all your ajax requests to not only verify that the server response is correct, but also that there wasn't an error defined in the response. You could write functionality into all your ajax requests to evaluate it, or you could just implement the change into the XHR object:

XHR.implement({
	isSuccess: function(status){
		if((status >= 200) && (status < 300)){
			if(this.transport.response && Json.evaluate(this.transport.response).error) return false;
			return true;
		}
	}
})

Using the XHR class

While XHR doesn't have the helper functionality of the Ajax class, you can use it directly if you like.

It takes the following options:

method
'post' or 'get' - the prototcol for the request; optional, defaults to 'post'.
async
boolean: asynchronous option; true uses asynchronous requests. Defaults to true.
onRequest
function to execute when the XHR request is fired.
onSuccess
function to execute when the XHR request completes.
onStateChange
function to execute when the state of the XMLHttpRequest changes.
onFailure
function to execute when the state of the XMLHttpRequest changes.
headers
accepts an object, that will be set to request headers.
encoding
the encoding, defaults to utf-8.
autoCancel
cancels the already running request if another one is sent. defaults to false.

Additionally, XHR has two properties that are notable (and by extension, Ajax and Json.Remote):

running
true if the request is running.
response
object, text and xml as keys. You can access this property in the onSuccess event.

Then you'll need to call the .send method to actually initiate a request. .send takes two arguments, the url, and the data to send.

var myXHR = new XHR({method: 'get'}).send('http://site.com/requestHandler.php', 'name=john&lastname=doe');

mootorial/07-remote.txt · Last modified: 2008/06/09 02:28 by nisimjoseph

On this page:

Page index