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.

Kayla Knight is a web designer and frontend web developer. She specializes in responsive web design, progressive web technologies, and also knows her way around most CMS’s and PHP. You can find out more and check out her portfolio at kaylaknight.co.

Comments

  1. / Reply

    AJAX is really NOT needed. It was patented AFTER I began using server controlled synchronous and asynchronous javascript.

    You can change the source of a script in the same way you can change the source of an image.

    Read what I wrote in the Talk pages for AJAX and follow the links.

    • Scott,
    • February 7, 2012
    / Reply

    Very strong explanation, the PHP stuff has never really bothered me I’ve always found it a lot more friendlier than JavaScript anyway, which is confusing as I consider myself more of a front end developer. Thanks for sharing…

  2. / Reply

    Incredibly comprehensive article. It’s good to see people are sharing their knowledge of proper javascript, giving us framework jockies a proper understanding of what is going on!

    Thanks!

    • Amit,
    • February 9, 2012
    / Reply

    Thanks a ton for sharing this info

  3. / Reply

    Not sure why you would not utilize the jQuery framework for these requests in a beginner tutorial; obviously better to know Javascript then it’s framework counterpart off the bat but there is no real benefit to doing this in this format especially for a newer scripter. More then likely they are not building dynamic web applicaitons of any real caliber so leading this into jQuery at the minimum would be much more sensible to me.

    1. / Reply

      Can’t fully agree with you. JQuery is a great framework for sure, BUT if you don’t understand the basic level of what happens in the “back” – you can’t go on.
      You just stick to the functionality that is provided by the framework and you’re STUCK there. I’m not saying you should learn JavaScript from A to Z, but you should learn the basics – that will help you evolve further.

      Anyways, thank you Kayla for sharing this tutorial – it’s a great one to start learning AJAX

  4. / Reply

    I’m sorry if I sounded condescending. I didn’t mean to but someone was offended enough to write a nasty comment in my contact page on my site. To him, I admit my web design is not good, I don’t enjoy that part of it. I enjoy the mathematics and logic more, and I like trying to re-invent the wheel. Every line of code I wrote, nothing is copy-pasted, I try as hard as possible to make things work just as well without javascript as with. I’ve built a resonably powerful cms and translating it between asp to php line for line where possible. I enjoy security, regular expressions, spam battles (that’s a hard one sometimes). If I could afford to have a team, includng graphic designers I would. The site’s I’ve done in my portfolio are for friends, who I assure you did not pay enough for a graphic designer. I also don’t enjoy writing that much, but do enjoy coding and carry on even when not paid. It’s my hobby that I’d like to make a living from :)

    Anyway, back to not sounding condescending. As I said, I didn’t mean to be. For a lot of people, who have a small, live script in their page loading an AJAX library is a waste of resources, both server side and client. By putting a variable into the querystring, I use live=1 and live=2, you can tell your php, asp, perl etc script to output it as javascript instead of html that it would usually output. You also set the headers accordingly. Using a script changer you can call that script as javascript. A cached script works like a function, and an uncached script works dynamically from the server. By adding a time in the querystring you can also force non-caching.

    It is a good method, and I noticed Facebook using it the other day in the output of their script for a like button on peoples’ websites. I didn’t add it, as it’s a massive security flaw to allow javascript from a 3rd party. Using a changing script function you can not only read the entire web page, but also read changes made whether dynamically or at user input.

    Maybe a guide to using script changers would be good as it’s a simpler introduction to live websites, which is what most are looking towards AJAX for.

    I hope I not dug the hole deeper……

  5. / Reply

    I found using lynda.com s easier to learn ajax, but this was very helpful.

    • jon,
    • May 25, 2012
    / Reply

    Great article Kayla, concise with friendly language. Hope you make more. I think the secret to effective learning is breaking it down, just as you’ve done into tiny manageable parts. Too many AJAX articles start off simple, then careen downhill into making JSON, XML ‘instant search’ functions and other advanced stuff.

    • amin,
    • August 5, 2012
    / Reply

    i want to add a persistent element into my website. it’s radio player. so i want a song of radio still playing even user navigate to any pages. please give a hint.

    • KAY,
    • August 16, 2012
    / Reply

    I am busy working on a 5 page website which requires a lot of photos, do you think I need ajax or rahter stay with PHP? If I need ajax do i have to put it on every page to avoid my website loading slowly or what do you think?

    Thanks
    \From Kay

    • kay,
    • August 16, 2012
    / Reply

    I forgot to ask you guys how to embed an audio player which plays a list of songs instead of the one I have which only play one song and thats it. Also I am having a problem embedding jsplayer with flash player. I have downloaded the latter but it just isnt working on my server as yet. frustration is ruling my judgement right now lol, pls help

    • ahmed,
    • October 18, 2012
    / Reply

    As much as I would thank you, still would not be enough for such detailed, practical article about ajax. Anyway thank you and please never stop making such beautiful articles.

    • Otis,
    • October 30, 2012
    / Reply

    I’m sorry, but I copied the code and it doesn’t work. Did you actually run the code you listed? Why do you have myData in one place and myDate in another? If code examples don’t work, then tutorials are useless.

    • Matthew,
    • December 18, 2012
    / Reply

    It’s a shame that your example doesn’t actually work.

      • Veronica Margot Paez,
      • August 9, 2013
      / Reply

      Sometimes it requires a little brain power to figure this thing out…just change one thing:

      Where it says “ajaxRequest.readyState” replace it with “xmlhttp.readyState” and the magic will start to happen!

      All it took was referencing W3CSchools to figure this one out. Do your homework. This is otherwise, a very thorough tutorial. +1.

    • Dave Gibelli,
    • March 23, 2013
    / Reply

    Example doesn’t work with IE or Firefox. The text is returned by the server but not displayed in the page.

  6. / Reply

    I think the coding above doesn’t work since if you look into the HTML code, it shows the DIV as and in the javascript code – the div is document.getElementById(“myData”) – so it appears the HTML myDate should be myData – that should make it work!

      • Martin_Shaisamufaro_Luther,
      • May 5, 2013
      / Reply

      Also change from “ajaxRequest.readyState == 4” to “xmlhttp.readyState == 4”

        • David Rivers,
        • June 15, 2013
        / Reply

        Thanks!

  7. / Reply

    Very good explanation! thanks for the article.

    • Farihin Fong Sho Ghi,
    • July 23, 2013
    / Reply

    Hi Kayla, thank you for the article. It’s good for people learning the rope, like myself. Never underestimate the basics… It’ll be great if you could update and correct those typos though. Otherwise great article and many thanks from me. :-)

    • sharvan,
    • September 21, 2013
    / Reply

    very nice tutorial thanx for this

Leave a Reply

Your email address will not be published. Required fields are marked *

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.