Performing ajax calls with jQuery, Dojo and Mootools

Introduction

In this tutorial we are going to look at how to perform ajax calls in the three of the most
popular JavaScript libraries out there: jQuery, Mootools, and Dojo.
First were going to look at how to perform simple ajax request using the POST and GET methods.
Next were going to submit forms using ajax.
Lastly we are going to submit and retrieve data using JSON.
Of course I’m going to show you how to do this in jQuery, Mootools, and Dojo.
Were going to use PHP for the backend as its the most popular server-side language at the time of writing
of this article. But if you’re a rubyist or a pythonista and want to learn ajax then worry not, most
of the PHP code that I used in this article are very simple and it should be easy to port them
into the language of your choice.
At the end of this article you will have an idea how each of these libraries handle
ajax calls.
So yeah let’s get started.

Including the Libraries

First let’s look at how they do things in jQuery. But to make sure nobody is left behind let’s first include the libraries that were going to use: jQuery, Mootools and Dojo:


		<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
		<script src="http://mootools.net/download/get/mootools-core-1.4.5-full-nocompat.js"></script>
		<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.7.2/dojo/dojo.js"></script>

	

You might be aware that jQuery and Mootools are both using dollar sign($) as an alias and this creates a conflict when you include the 2 libraries in the same page. Here’s a very good article from David Walsh on how to use jQuery and Mootools together:
Using jQuery and MooTools Together

Always remember to include your scripts after your html, preferably after the body tag as mentioned in this article from yahoo:
Best Practices for Speeding Up Your Website

jQuery $.post

Once you’re done with that create a new PHP file. This will be the file that were gonna be talking to in the backend using ajax.

Going back to our main file (the file in which we linked to jQuery) we create a new object called names and an array called letters:

		var names = {
			name: 'cool',
			names: ['pizza','coffee','milk','c2']
		}

		var letters = ['abc','def','ghi'];
		

Next we submit it using the $.post method which requires one argument and two optional arguments. First is the name of the file in the server that we want to talk to (ajaxback.php), second is the collection of data that we want to submit to that file, third is the callback function in which we specify what we want to do after the the call has been made. Just like when making a phone call, first you must have someone to call which is defined by the phone number of the person that you’re going to call, second you must have things to talk about, third what you want to do once you’ve said everything that you want to say.

		$.post('ajaxback.php', {'names' : names, 'letters' : letters}, function(data){

			console.log(data); //output what's returned by ajaxback.php
		
		});
		

Dojo xhrPost

The dojo equivalent of the $.post method in jQuery is the xhrPost method which requires three properties. First is the url which is the file in the backend in which you want to submit data, second is the content in which you can simply specify an object(key-value pair), and then the load in which you specify a function to be executed once the ajax call has been made.

		dojo.xhrPost({
			url: "ajaxback.php",
			content: {'names' : names, 'letters' : letters},
			load: function(data){
				console.log(data);
			}
		});
		

Mootools POST Request

The same thing can be done using mootools by creating a new instance of the Request class which has pretty much the same options as the xhrPost in dojo.
The method which is basically the method that you’re going to use to submit the data in this case were using POST.
Next is the url which is pretty much the same as the url property in xhrPost, there’s also onComplete in which you specify a function that will be executed once the ajax call is completed. Finally you need to call the send() method to send the request into the backend.

	
		var post_req = new Request({
			method: 'POST',
			url: 'ajaxback.php',
			data: {'names' : names, 'letters' : letters},
			onComplete: function(data){
				console.log(data);
			}
		}).send();
		

Accessing data submitted via POST in the backend

For our PHP file(ajaxback.php) we simply output everything that has been submitted via the $.post method in jQuery:

		<?php
			//output everything submitted via POST method
			print_r($_POST); 
		?>
		

jQuery $.get

We can also submit data using the $.get method which works pretty much like the $.post method but the only difference is that it submits the data using the GET method. Here’s how:

			$.get('ajaxback.php', {'name' : 'son gohan', 'technique' : 'awesome'}, function(data){
				console.log(data);
			});
		

Dojo xhrGet

The Dojo equivalent of $.get in jQuery is the xhrGet method

		dojo.xhrGet({
			url : "ajaxback.php", 
			content : {'name' : 'son gohan', 'technique' : 'awesome'},
			load : function(data){
				console.log(data);
			}
		});
		

Mootools GET Request

The same thing can be done in Mootools by just changing the method option to GET.

		var gets = new Request({
			method: 'GET',
			url: 'ajaxback.php',
			data: {'name' : 'son gohan', 'technique' : 'awesome'},
			onComplete: function(data){
				console.log(data);
			}
		}).send();
		

Accessing data submitted via POST in PHP

There’s not much of a difference except that if you have to access the data in the backend you will no longer use the $_POST you will use $_GET instead:

		<?php
			echo "name: " . $_GET['name']."\n";
			echo "technique: ". $_GET['technique']."\n";
		?>
		

Submitting Data with both POST and GET in jQuery

But you can also submit data using both POST and GET methods here’s how:

		$.post(
				'fakepost.php?name=songoku&technique=kamehamewave', 
				{'name' : 'son gohan', 'technique' : 'awesome'}, 
				function(data){
					console.log(data);
				}
		);
		

In the example above we still used the $.post method for submitting the data
but we appended a query string in the url(name=songoku&technique=kamehamewave), this query string is submitted via the GET method but the key-value pair that we used in the data part will still be submitted via POST method.

Submitting Data with both POST and GET in Dojo

Of course we can also do the same trick in dojo.

		dojo.xhrPost({
			url : "fakepost.php?name=songoku&technique=kamehamewave",
			content : {'name' : 'son gohan', 'technique' : 'awesome'},
			load : function(data){
				console.log(data);
			}
		});
		

Submitting Data with both POST and GET in Mootools

The same thing can be done in Mootools by simply passing in a query string after the url and then specifying a key-value pair on the data option:

		var gets = new Request({
			method: 'POST',
			url: 'gets.php?name=songoku&technique=kamehamewave',
			data: {'name' : 'son gohan', 'technique' : 'awesome'},
			onComplete: function(data){
				console.log(data);
			}
		}).send();
		

Accessing data submitted via POST and GET in PHP

We can then access it in PHP(fakepost.php) using both $_POST and $_GET:

		echo "Im accessed via GET method\n";
		echo "name: " . $_GET['name']."\n";
		echo "technique: ". $_GET['technique']."\n\n";

		//Accessing data using $_POST method
		echo "Im accessed via POST method:\n";
		echo "name: " . $_POST['name']."\n";
		echo "technique: ". $_POST['technique']."\n";
		

Updating DOM with AJAX content in jQuery

Next thing that I’m going to show you is how to load the data returned from the backend into the DOM. In other words updating the contents of an existing element in the DOM.
We can do it by simply applying our knowledge in jQuery and use the $.post and $.get methods like this:

			<div id="container">
				
			</div>

			<script>
			$.post('load.php', {'name' : 'picollo', 'age' : 44}, function(data){
				$('#container').html(data); //load the data into the div with the id of container
			});
			</script>
		

As you can see from the code above we simply set the html(the same as innerHTML in plain JavaScript) to the data returned from the backend.


We can pretty much live by just doing that but jQuery has methods created specifically for loading or updating the contents of an existing element. One of such methods is the $.load method which is also very similar to the $.post and $.get methods. You just need to call it from the element where you want to load the new content, the arguments that it requires is pretty much the same with $.post and $.get. Here’s how to use it:

		<div id="container">
				
		</div>

		<script>
		$('#container').load('load.php', {'name' : 'picollo', 'age' : 44});
		</script>	
		

The code above does the same thing as our previous example except that we cut the lines of code from 3 lines to just 1 line (excluding the html code).

Updating DOM with AJAX content in Dojo

We can also do this in Dojo by using either xhrPost or xhrGet. All you have to do is to set the innerHTML of the element that you’re trying to update equal to the data returned from the backend.

		var string_json = JSON.stringify(obj);
		dojo.xhrPost({
			url : "load.php",
			content : {'name' : 'picollo', 'age' : 44},
			load : function(data){
				dojo.byId('container').innerHTML = data; //update contents of container
				/*
				you can also do this by using a native Dojo helper method
				dojo.html.set(dojo.byId('container'), data);
				*/
			}
		});
		

Updating DOM with AJAX content in Mootools

We can do the same thing in Mootools using the set helper method to set the html of the element that were trying to update after the request has been completed.
In this case the div with the id of container.

		var req = new Request({
			method: 'POST', 
			url: 'load.php',
			data: {'name' : 'picollo', 'age' : 44}, 
			onComplete: function(data){
				$('container').set('html', data); //update contents of container
			}
		}).send();
		

And for our backend we simply output what has been submitted via $.post method. This will then be loaded into the div with the id of container as you have seen from the code above:

		<?php
			echo "Name: ". $_POST['name']. "<br/>";
			echo "Age: ".$_POST['age'];
		?>
		

Using $.ajax in jQuery

The $.post and $.get methods are just convenience methods. Methods that were created for the convenience of our poor little fingers. If you want more options like disabling the cache, specifying the content type, data type, specifying error or success callbacks then what you need is the BIG Mama the $.ajax method. Everything you need to know about the $.ajax method is in the jQuery documentation but I’m gonna show you an example of how to do things to get you started.

Here’s how to use the $.ajax method in simplest terms:

		$.ajax({
			type: 'POST', //method for submitting: either GET or POST
			url: 'ajaxback.php', //file in the backend that you're talking to
			data: {'names' : names}, //data to submit
			success: function(data){ //what you want to do once the data is submitted
				console.log(data); //output what's returned by ajaxback.php
			}
		});
		

Using the $.ajax method you can also specify things like the cache and statusCode.
Cache if you want to cache the page that you’ve specified in the url then use true as its value,
if its a page thats constantly updated then use false.

StatusCode is useful if you’re performing ajax calls on a different domain because the page that you’re referring to might not always be available maybe they’re doing a maintenance on the server. Here’s how to use it:

			statusCode:{
				404:function(){
					//what you want to do if the page you're referencing is not found
				},
				403:function(){
					//what you want to do if page is forbidden
				}
			}
		

If you want to know more about status codes then visit this link: Status Codes

AJAX in Dojo

xhrGet and xhrPost in Dojo are pretty much the equivalent of $.ajax method in jQuery since there’s already a bunch of options that you can use like the form in which you simply specify the form that you will use as a data source by using dojo.byId(‘idOfTheFormToUse’), there’s also load option in which you can define the function that you want to execute when the request has been successfully made, there’s also the error option in which you can specify a function that will execute when the request failed, there’s also handle option which let’s you define a function that executes whether or not the request suceeded.

AJAX in Mootools

The Request class in Mootools is already fully packed with options that you can use to customize how you send ajax requests to the backend.
There’s a bunch of options that you can use here’s the documentation

JSON as a data source

Next I’m going to show you how to retrieve JSON from the backend to do that create a new php file(json.php) this will serve as our data source. In the code below were simply creating a new array called $things which has a collection of blogs and people in it. Then we just convert it to JSON string using the json_encode() method
Note that in the code below were using PHP5.4 syntax in defining the array. So we won’t have to switch from JavaScript to PHP minds when defining arrays.

		<?php
		$things = [
					'blogs'=>['smashing magazine', 'codrops', 'sixrevisions', 'nettuts', 'coding horror'],
					'people'=>['john resig', 'jeffrey way', 'chris coyier', 'paul irish']
				];
		/*for PHP5.3 and below
		$things = array(
			"blogs"=>array("smashing magazine", "codrops", "sixrevisions", "nettuts", "coding horror"),
			"people"=>array("john resig", "jeffrey way", "chris coyier", "paul irish")
		);	
		*/		
		$json_things = json_encode($things); //convert array to json string
		echo $json_things; 
		?>
		

Retrieving JSON in jQuery

Next I’m going to show you how to retrieve JSON from the backend and output them in the console.
Were going to use $.post for this one. Note that were expecting a JSON string from the backend.

		$.post('json.php', function(data){
			
			var json_data = JSON.parse(data); //convert JSON string into object
			
			console.log("Awesome Blogs: \n");
			for(var blog in json_data.blogs){ //loop through the blogs
				console.log(json_data.blogs[blog]);
			}
			
			
			console.log("\nAwesome People: \n");
			for(var awesome in json_data.people){ //loop through the awesome people
				console.log(json_data.people[awesome]);
			}
		});
		

Retrieving JSON in Dojo

We can do the same thing in Dojo by specifying JSON as the value for the handleAs option.
This is the same as doing JSON.parse(data) when using plain JavaScript:

		dojo.xhrPost({
			url : "json.php",
			handleAs : "json", 
			load: function(data){
				dojo.forEach(data.blogs, function(row){//loop through the blogs
					console.log(row);
				});

				dojo.forEach(data.people, function(row){//loop through the awesome people
					console.log(row);
				});
			}
		});
		

Retrieving JSON in Mootools

The same thing can be done in Mootools but instead of just creating a new instance of the Request class
we use Request.JSON which automates receiving of JavaScript Objects in JSON format.
We can then use Object.each to loop through
the object.

		var json_req = new Request.JSON({
			url : 'json.php',
			onSuccess : function(json_obj, json_string){//json_obj is the object representation of the json_string
				console.log(json_obj); //this returns an object

				//loop throug the contents of the object	
				Object.each(json_obj.blogs, function(value, key){
					console.log(value);
				});
			}
		}).send();
		

Submit Form via AJAX in jQuery

Finally I’m going to show you how to submit a form via ajax. For that were gonna need a sample form.
The first form(form_sample) is a simple form which has only text fields in it. The second form(form_another)
is also a pretty simple form but were using it to submit an array(notice the name attribute of the fields has open and close brackets after the actual name of the field).

		<form id="form_sample">
			<p>
				<label for="name">Name:</label>
				<input type="text" name="one_name" id="one_name" value="hisoka">
			</p>
			<p>
				<label for="language">Language:</label>
				<input type="text" name="one_language" id="language" value="japanese">
			</p>
		</form>

		<form id="form_another">
			<p>
				<label for="name">Name:</label>
				<input type="text" name="name[]" id="name1" value="killua">
			</p>
			<p>
				<label for="name">Name:</label>
				<input type="text" name="name[]" id="name2" value="irvine">
			</p>
			<p>
				<label for="name">Name:</label>
				<input type="text" name="name[]" id="name3" value="vahn">
			</p>
		</form>
		

For jQuery were simply going to serialize the form using the $.serialize method which simply converts the form to its query string representation(name-value pair separated by &). All you need to do is to call serialize() on the element that you want to serialize, in this case the form_sample which we select by using its id:

		var form = $('#form_sample').serialize();
		console.log(form);
		/*
		output:
		one_name=hisoka&language=japanese
		*/
		

After serializing the form we simply submit it via the $.ajax method:

		$.ajax({
			type : "POST",
			url : "submitform.php",
			data : form, //name of the serialize form
			success: function(data){
				console.log(data); //output what's returned from submitform.php
			}
		});
		

Submit Form via AJAX in Dojo

In dojo we can pretty much submit a form via ajax in just one step, we simply need to specify a value for the form property no need to serialize the form:

		dojo.xhrPost({
			url : "submitform.php",
			form : dojo.byId("form_sample"), //get form by its id
			load : function(data){
				console.log(data); 
			}
		});
		

Submit Form via AJAX in Mootools

We can do the same thing in Mootools by using toQueryString() method which simply converts a form into a query string which is pretty much the same with the serialize() method in jQuery.

		//toQueryString returns: "one_name=hisoka&one_language=japanese"
		//parseQueryString returns the object representation of the query string
		var form_data = $('form_sample').toQueryString().parseQueryString();

		var form = new Request({
			method : 'POST',
			url : 'submitform.php',
			data : form_data, 
			onComplete : function(data){
				console.log(data);
			}
		}).send();
		

You can then access the submitted data in the backend:

		<?php
		echo "Name: ".$_POST['one_name']. "\n";
		echo "Language: ".$_POST['one_language'];
		?>
		

Submit Array Form via AJAX in jQuery

Next we try to submit the other form(form_another) as you can see from the code below the output when we call serialize from it is a little bit different from the sample_form, more like bizzare I guess that’s why I did a quick Google search and found out that it’s called percent encoding it’s pretty much the way how space, open bracket, and close bracket are represented via url encoding:

		var another_form = $('#form_another').serialize();
		/*
		output:
		name%5B%5D=killua&name%5B%5D=irvine&name%5B%5D=vahn
		*/
		

Simply submit it the usual way:

		$.ajax({
			type : "POST",
			url : "submitform.php",
			data : another_form, //name of the serialize form
			success: function(data){
				console.log(data); //output what's returned from submitform.php
			}
		});
		

Submit Array Form via AJAX in Dojo

For dojo we simply repeat what we did earlier for the first form(form_sample), select the form via id and specify it as the value for the form property:

		dojo.xhrPost({
			url : "submitform.php",
			form : dojo.byId("form_another"), //get form by its id
			load : function(data){
				console.log(data);
			}
			error : function(){
				//just in case you're unlucky and your ajax request/call didn't suceed the code here will be executed
			}
		});
		

Submit Array Form via AJAX in Mootools

Submitting the other form(form_another) is pretty much the same with Mootools.

		//toQueryString returns: "name%5B%5D=killua&name%5B%5D=irvine&name%5B%5D=vahn"
		//parseQueryString returns the object representation of the query string
		var form_data = $('another_form').toQueryString().parseQueryString();

		var form = new Request({
			method : 'POST',
			url : 'submitform.php',
			data : form_data, 
			onComplete : function(data){
				console.log(data);
			}
		}).send();
		

You can then access it in the backend(submitform.php) by looping through the contents of $_POST[‘name’] where name is the name of the field that was repeated(name=”name[]”).

		<?php
		foreach($_POST['name'] as $row){
			echo "\t".$row."\n";
		}
		?> 
		

Conclusion

We’ve only scratch the surface of performing ajax calls in jQuery, Mootools and Dojo in this article but hopefully I was able to give you a good introduction so that you can start using them with ease and be able to further your knowledge in this topic. I was also able to gain a fair amount of knowledge as I was researching these. If you have any questions or if you have notice something that is incorrect in this article feel free to share them in the comments as we are all both learning. You can hit the links in the resources if you want to learn more about doing ajax in each of the libraries discussed in this article. Thank you!

Resources

Advertisements

One thought on “Performing ajax calls with jQuery, Dojo and Mootools

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s