A Beginner’s Guide to Using AJAX in Your Website

A Beginner's Guide to Using AJAX in Your Website

AJAX is a method that has been around for a while, yet in the past was not something that was used by many developers. Only recently has it been gaining more attention, especially with the rise in web applications that demand a better user experience. AJAX is not a programming language in itself, but rather a new way to use JavaScript in relation to a web page, and it’s this new technology that can make web pages faster, more user-friendly, and the overall function more efficient.

AJAX stands for Asynchronous JavaScript and XML, and is used for updating and interacting with a server via JavaScript, therefore allowing far more functionality with the server without having to reload the web page. In this article, we’ll go over the basics for implementing AJAX into your website.

A Beginner's Guide to Using AJAX in Your Website

If You Know JavaScript, AJAX is Easy

If you understand at least the basics of JavaScript, you’ll be able to pick up AJAX quite easily. You can make a page interact with the user with JavaScript alone, and then based on those user interactions you can send, receive, or update page content in relation to the server’s response when needed.

Let’s say we have a simple button, and we want it to update some data on the page. Imagine we have some input fields before this that the update button will take care of.

<button onclick="updateProfile()" type="button">Update</button>

As seen in the button code above, upon clicking on the button, we can call a JavaScript function updateProfile(). If you know JavaScript, there’s nothing new there. The function that is defined between script tags will then be called:

<script type="text/javascript">
function updateProfile(){
	// JavaScript code to be executed
}
</script>

As is best practice, these script tags and all code in between can be placed right before the body tag. Alternatively the JavaScript can be placed within the header (depending on the site structure or specific need for this page, it may be smarter). Of course, with larger pieces of code, it should be placed within a JavaScript file .js and the file should be included in the header.

From here on, we can place any code we want executed when that button is pressed inside of this function. Again, nothing new here. With traditional JavaScript, we could manipulate any content that is already in the page, as long as it didn’t need any more data from the server.

If we needed additional data from the server, we would need to bring in a server-side scripting language and reload the page entirely. That’s where AJAX comes in — to solve this problem. Within the updateProfile() function, we can use AJAX code to interact with the server (via JavaScript!), and we are now able to retrieve, update, and delete information as needed on the server, no reload required.

<script type="text/javascript">
function updateProfile(){
	// JavaScript code to be executed
	// AJAX code will go here as well!
}
</script>

The XMLHttpRequest and ActiveXObject Objects

In order to begin using AJAX code, you need to tell the browser that it will be interacting with the server. In JavaScript there are two objects that help AJAX work: the XMLHttpRequest and ActiveXObject objects. While these are the basis for object-oriented programming with JavaScript, you don’t need to understand or implement object-oriented concepts to an extent to use AJAX. In fact, we’ll walk you through it right here.

Both objects do the same thing, but they are just meant to support different browsers. The objects are meant to exchange and handle data with the server behind the scenes of the web page; simple as that.

To tell the browser you will be using AJAX, use the following code (Credit to W3Schools):

<script type="text/javascript">
function updateProfile(){
	// Create a variable to refer to our request object:
	var xmlhttp;
	
	if (window.XMLHttpRequest){
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}else{
		// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
}
</script>

The code above is pretty simple. First, we create a variable that will hold our object; whether it is a XMLHttpRequest or ActiveXObject will be dependent on what browser the user is in. (Remember, they both do the same thing.) If we can detect that our browser can handled the XMLHttpRequest object via window.XMLHttpRequest, then we can set our variable to this object. Otherwise, we should set it to the ActiveXObject.

This will be the start of any AJAX code you place into a website. Note that if you are using multiple functions, it may not be the most efficient solution to declare this code at the beginning of every function. If used within several functions, it would be more efficient to set this variable on page load.

Receiving Requests from the Server

Now that AJAX is “all set up” for use in our browser, we can begin the fun part – interacting with our server. Whichever request object is used (based on the browser), there are a set of pre-defined functions we can use to get information from a server via AJAX, send information, or manipulate information.

The first pre-defined property we’ll look into is the onreadystatechange property. This does just what it says, it calls the function it holds (see below) when the readyState is changed. The readyState is just the state our server tells us it’s in: processing, downloading, or completed.

xmlhttp.onreadystatechange = function(){
	// This code will be executed each time the readyState changes
}

Each readyState is defined by a number, and we can check to see if our current readyState equals that number to process our code dependent on what the server’s doing:

  • ajaxRequest.readyState == 0 // request not initialized
  • ajaxRequest.readyState == 1 // server connection established
  • ajaxRequest.readyState == 2 // request received
  • ajaxRequest.readyState == 3 // processing
  • ajaxRequest.readyState == 4 // completed and response is ready

For example, if we wanted to execute some code only after the data or actions we’ve requested are ready and have our feedback for us, we’d check to make sure our readyState was at 4:

xmlhttp.onreadystatechange = function(){
	// This code will be executed each time the readyState changes
	if(ajaxRequest.readyState == 4){
		// This code will be executed if our request 
		// is completed
	}
}

We can access the data we’re requesting by using either the responseText or responseXML properties respectively. responseText is for retrieving text-based data, while responseXML can be used for retrieving XML based data. Then, using basic JavaScript again, we can use these properties to assign our feedback from the server in a div, or do whatever else we like with it:

xmlhttp.onreadystatechange = function(){
  // This code will be executed each time the readyState changes
  if(ajaxRequest.readyState == 4){
     document.getElementById("myData").innerHTML=xmlhttp.responseText;
  }
}

Hopefully you can understand the logic behind all this, but of course none of the above will do us any good as long as we don’t tell our code what we want to request in the first place. We needed to create a function to handle our request first, and the above code simply explains how we’ll show our data from the server after we’ve requested it.

Sending Requests to the Server

Like with receiving responses from the server, our request object also has pre-defined properties and functions for dealing with sending requests to the server. Anytime we need to send new information, manipulate information, or send instructions of any type to work with our web application, we’ll be sending a request to the server. After we’ve sent the request, we can turn around and use the function we created above (using onreadystatechange) to see our results.

There are two parts to sending a request to the server via AJAX, as seen in the example below:

xmlhttp.open("GET","ourPHPCode.php",true);
xmlhttp.send();

The first prebuilt function, open(), let us define what server-side script we’ll be using to communicate with the server. We include our server-side script as the second parameter and it will be processed without refreshing the page. This function also holds a few other arguments that we’ll look into in more detail soon.

Included in our server side script ourPHPcode.php, we’ll include the more in-depth instructions that will work with our server. After AJAX opens the server-side script file via the open() method, we can send those instructions out via the send() method.

<script type="text/javascript">
function updateProfile(){
	// Let's first create our request object:
	var xmlhttp;
	
	if (window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	// This code will be executed each time the readyState changes
	xmlhttp.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			document.getElementById("myData").innerHTML=xmlhttp.responseText;
		}
	}
	
	// We'll send any data to the server through our request object
	xmlhttp.open("GET","ourPHPCode.php",true);
	xmlhttp.send();
}
</script>

A Closer Look at Open()

When we are opening a file to send to the server via AJAX, the most important portion item is the link to our server-side file. Beyond this though, we have two more: the method for sending the request and async.

open(method,file,async);
Example: open("POST", "myFile.aspx", false);

The method for the open() function can either be GET or POST. If you are familiar with PHP (and many other similar languages) and sending data via HTML forms, the concept is much the same. GET can be used in most situations, and you can even send values through a URL like with HTML forms:

open("GET", "ourPHPCode.php?email=test@test.com&firsname=Johnny&lastname=Smith", false);

GET will often times get you a cached result, which you may not always want. If you still would like to use the GET method, you can simply create a “new, fresh URL” for the browser to go to by appending a unique ID, so it will send you an uncached result:

open("GET", "ourPHPCode.php?x=", false);

POST can be more secure than GET, and also has no size limitations. If you’re ever working with data sensitive information (like passwords), then use “POST”.

Async, the last parameter, can either be set to true or false. You’ll want to use true the majority of the time, and false can sometimes be used for smaller requests. Setting asynchronous to true simply means you’ll be able to do other functions while your AJAX request is waiting for the server response. (It’s recommended.)

Working with a Server-Side Language

After we’ve set up our AJAX to request information from a server-side script and also to handle its response, there’s really nothing new or magical about our server-side script. The code is the same, and whatever you do with it will follow the same syntax as always. All AJAX does is help to be the middleman while this script executes and handles all the dirty work, allowing us to eliminate or cut down on the need for page refreshes, and allowing us to execute other functionality on a page while our server-side script is working with the server.

Let’s say we simply want to echo out a string (via PHP) when we change some form input. We’ll use our function that we created above, which defines our AJAX request object, tells the browser what to request, and where to put the response.

Our HTML file (with our AJAX/JavaScript):

<html>
<head>
<script type="text/javascript">
function updateProfile(){
	// Let's first create our request object:
	var xmlhttp;
	
	if (window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	// This code will be executed each time the readyState changes
	xmlhttp.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			document.getElementById("myData").innerHTML=xmlhttp.responseText;
		}
	}
	
	// We'll send any data to the server through our request object
	xmlhttp.open("GET","ourPHPCode.php",true);
	xmlhttp.send();
}
</script>
</head>
<body>
	<input name='firstName' onChange='updateProfile()' />

	<div id="myDate"></div>
	<!-- Our response will be placed into the div above,
	thanks to JavaScript's "innerHTML" property. -->
</body>
</html>

Our PHP file ourPHPCode.php.

<?php
	echo "The input field was changed.";
?>

Using JavaScript’s onChange event, we trigger our JavaScript function, updateProfile(). Within this function we’ve done all our AJAX set up, and sent a request to our PHP file, ourPHPCode.php, which simply echoes back our string. Therefore, we use the power of AJAX to echo out this string when our input field is changed. There is no need for refreshing or waiting on a slow response from a server.

Obviously, this example is incredibly simple and very pointless. This is just, at the most basic level, how we can connect a server-side script with an HTML page using the power of AJAX. Within the PHP script, you can take in data from a form (for example if we used the POST method in our open() function, we could just use PHP’s $_POST variable to obtain that information), manipulate it, send it to a server, update information in a database, and return a response via PHP’s echo statement.

Let’s say we have a simple HTML form that asks for a name and email. Below is an example of something more elaborate:

Our HTML/JavaScript page:

<html>
<head>
<script type="text/javascript">
function updateProfile(){
	// Let's first create our request object:
	var xmlhttp;
	
	if (window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	// This code will be executed each time the readyState changes
	xmlhttp.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			document.getElementById("myData").innerHTML=xmlhttp.responseText;
		}
	}
	
	// We'll send any data to the server through our request object
	xmlhttp.open("GET","ourPHPCode.php",true);
	xmlhttp.send();
}
</script>
</head>
<body>

	<form>
	<label>First Name;</label><br />
	<input type='text' name='firstName' />
	
	<label>First Name;</label><br />
	<input type='text' name='lastName' />
	
	<label>First Name;</label><br />
	<input type='text' name='email' />
	
	<input type=submit' onClick='updateProfile()' />
	
	</form>

	<div id="myDate"></div>
	<!-- Our response will be placed into the div above,
		thanks to JavaScript's "innerHTML" property. -->

</body>
</html>

Our PHP Script:

<?php
	$firstName = $_POST['firstName'];
	$lastName = $_POST['lastName'];
	$email = $_POST['email'];
	
	$response = '';
	
	// Now you have variables from the form, and you can do whatever with them:
	// validate them, update a database, insert them into a database, or whatever.
	// You can do whatever you'd normally do with regular PHP here.
	
	// You can then create a response variable, set it to whatever value you'd 
	// like to send back to the user, and AJAX will update it automatically.
	
	// Examples:
	
	if(// Email isn't valid){
		$response = "The email address you entered isn't valid.";
	}
	
	if(// Everything checks out ok and was submitted properly){
		$response = "Your profile has been updated!";
	}
	
	echo $response;
?>

The above shows how we can manipulate form data, and one can see that there’s no difference in how we use our PHP code to work with a server. We could also include a link to a database connection and work with a database with the information we grabbed from the same page. Just like an HTML form or otherwise can use POST to send data, so can AJAX. From a server-side script’s perspective, it’s all the same.

Conclusion

AJAX is a revolution to web technology, allowing our client-side scripting to reach server data as needed, yet still allowing us to code with the faster and often times more user-friendly benefits of client-side. It’s been around for a while, but it’s great to see now how AJAX is really taking off as common practice.

While there are endless tutorials on the web for doing specific things with AJAX, such as creating chat boxes, live feeds, updating info on the fly, and so much more, it’s more important than ever to understand the basis of how AJAX works. Having a true understanding of AJAX can help any developer to use the technology to the fullest and in a wide variety of situations most efficiently.

Deals

Iconfinder Coupon Code and Review

Iconfinder offers over 1.5 million beautiful icons for creative professionals to use in websites, apps, and printed publications. Whatever your project, you’re sure to find an icon or icon…

WP Engine Coupon

Considered by many to be the best managed hosting for WordPress out there, WP Engine offers superior technology and customer support in order to keep your WordPress sites secure…

InMotion Hosting Coupon Code

InMotion Hosting has been a top rated CNET hosting company for over 14 years so you know you’ll be getting good service and won’t be risking your hosting company…

SiteGround Coupon: 60% OFF

SiteGround offers a number of hosting solutions and services for including shared hosting, cloud hosting, dedicated servers, reseller hosting, enterprise hosting, and WordPress and Joomla specific hosting.