Home > Web > Learn AJAX in 25 minutes. Maybe 30.

Learn AJAX in 25 minutes. Maybe 30.

April 1st, 2008

Ajax

I remember when I was first asked if I knew AJAX a few months ago. At the time I only had a small idea of what it was. I knew it had something to do with displaying dynamic content without having to refresh the browser. As I started tweaking my resume and started my job search, I noticed that everyone and their mom was looking for people who “knew” AJAX. I figured I might as well learn it. I did what I usually do when I want to learn something new. I went and bought a book. I decided on “Ajax for Dummies.” I had good experiences with the dummy series of books in the past. I took it home and started skimming through it, disappointed to find that AJAX wasn’t something new at all. It’s not even it’s own language or anything. It’s just a way of using JavaScript. To narrow it down even more, the “meat and potatoes” of AJAX is just one stinkin’ object. If you can copy/paste code and understand what’s happening you “know” AJAX and you can put it on your resume. So without further ado, let me explain how it works and what this magical object is. This is designed for people who have an understanding of PHP and JavaScript.

How AJAX Works

As mentioned earlier, AJAX is just JavaScript. So for your AJAX code you’re going to want to put it in <script language =”javascript”></script> tags in the header of your page. You will have code to initialize an object and you will have a function that is called somewhere in your <body>. Usually it’s going to be a form element that calls the function. You could also possibly have functions that listen for events as well when you are getting into more complicated procedures.

The main object of AJAX is called XMLHttpRequestObject. Your first goal is going to be to create one of these objects. It’s not as simple as initializing a new object though. IE and Firefox handle the object differently so you are going to need some conditional code. Your next goal is going to be to setup a function that can take a DIV id as an input and also a page that is going to be executed and the output is going to be displayed in the DIV that was passed to the function. This is all happening asynchronously, meaning the browser doesn’t have to refresh to display the output from the specified page. So the run down looks like this:

  1. XMLHttpRequestObject is created.
  2. User enters something in a form and presses a submit button which calls a function in your AJAX code.
  3. The function called takes in a target DIV and a page to be executed asynchronously.
  4. The output of the specified page is then copied into the DIV that you want it to be.



I am going to give you all the code you need to copy/paste to get some AJAX going and then I explain the important parts of it.

The Code

Sample AJAX Page

Take a look at the code. You will see that the first two conditionals are for creating the object. The first condition is for Firefox and the second one is for IE. After those lines you will have an XMLHttpRequestObject. getData is the function that does all the action and will be called somewhere in your <body>.

You will notice in the getData function I initialize a variable and modify one of the inputs to the function.

var extra = document.form1.name.value;
dataSource = dataSource + ‘?data=’ + extra;

This is taking advantage of JavaScript. The function is called when the user hits submit,therefore at the time of submission, the value of the text box is known. That value can be accessed using document.form1.name.value. Form1 is the name of the form in which the text box is in. I’m taking the value of what is in the text box and im adding it to the dataSource in the form of sample.php?data=extra. So when my dataSource (sample.php) is executed, I can pass it the information that was entered into the text box.

The rest of the code is pretty procedural if you understand JavaScript.

var obj = document.getElementById(divID);

This is just allowing for access of divID’s properties by getting its element id and putting it in a variable called obj.

XMLHttpRequestObject.open(”GET”, dataSource);

This line is setting up the XMLHttpRequestObject object to be able to open a connection to the dataSource. No connection is made yet though. “GET” is specified to retrieve information. You can use “POST” to send information, but for most AJAX purposes you are going to be using “GET.” In the case of sample.html, sample.php is the datasource. So this is the file that is going to be executed when the user hits submit.

XMLHttpRequestObject.onreadystatechange = function()

This is an anonymous function. JavaScript allows for anonymous functions inside of other fucntions. Basically this function is going to be automatically called whenever the XMLHttpRequestObject goes through a change. The changes you care about are the change of status and change of the readyState. When readyState is equal to 4, this means your data has been downloaded. When the status is equal to 200, everything went ok.

So when all your data has been retrieved you want to take that data and display it in the targetDiv. This is is done by the following line of code:

obj.innerHTML = XMLHttpRequestObject.responseText;

Whatever was in your <targetDiv></div> tags just got replaced by data that you retrieved from sample.php.

The HTML portion

The HTML portion of sample.html is just a simple form. The form has the following property:

onsubmit=”getData(’sample.php’, ‘targetDiv’)”

When the user submits the form, the getData function is called passing it the values of sample.php and targetDiv. targetDiv is the name of the DIV that I want the data to be displayed in. Sample.php is the file that is being executed asynchronously.

In the AJAX code, remember that I modified sample.php to be sample.php?data=extra where “extra” is the value of what is in the text box at the time of form submission. I did this so I can pass that information and then retrieve it in sample.php.

What’s in sample.php

Not much. It’s about 7 lines of code. I use $_GET["data"] to fetch the value of data. That value is a number entered in by the user and passed by the getData function. I then set up a for loop to run “data” number of times and echo the word “Shabam.” Take note if the user enters in the box something like “asdasf” and not a number, nothing is going to be displayed.

It’s important to note that if I didn’t echo anything, nothing would have been displayed in sample.html. Only the output of the php file is going to be passed back to the HTML file and displayed.

Adding on to the basic sample to do cooler stuff

Note that the function getData in sample.html is only called when the user submits the form. Apps like facebook, where you type in part of a friend’s name and then it displays a list of your friends whose name starts with what you’ve typed so far, use AJAX. Yes that sentence was loaded and structured poorly.

In sample2.html when text is being entered into the text box, it performs the operation without having the user to press a submit button.

The Code

Sample AJAX Page 2

There are only two differences. The first difference is that there is an added function called getSuggest. This function is going to be called whenever something is entered into the text box. How is that done?

<input type=”text” name=”name” id=”textfield” onkeyup=”getSuggest(event)” />

This is the second difference. Using the “onkeyup” property of the text box, we can call the getSuggest function. The getSuggest function takes in a keyEvent as input. It checks the input to see if it is of the type “onkeyup.” If it is, then the function is going to call getData and everything is going to work like it did in the first example. The same sample.php file is being used. getSuggest is going to be called everytime the text inside of the text box is modified.

A few more notes

Form elements have different properties. If you are using a list/menu, you can use the property “onchange” to trigger the getSuggest function and then in getSuggest, instead of checking for “keyup” check for “onchange.” So whenever a user selects something from a list, you can have data pulled up asynchronously. This is pretty handy for narrowing down searchs and what not.

The X in AJAX stands for XML, but nothing I did had anything to do with XML. All the data I was retrieving was formatted as regular text. If I wanted to retrieve XML data I would be using obj.innerHTML = XMLHttpRequestObject.responseXML instead of obj.innerHTML = XMLHttpRequestObject.responseText.

If you have any further questions or comments, don’t be afraid to send them in my direction!

admin Web ,

  1. October 28th, 2008 at 17:04 | #1

    You write very well.

  1. No trackbacks yet.