AJAX - A simple Introduction

AJAX has became the new buzz word of the internet, but what is it? and what does it actually do?

Introduction

Suppose we have a webpage, displaying news.

Now, for the user to switch from one news story is pretty unefficient.
The only part of the webpage that changes is the news content area, though the whole page (graphics and all) is reloaded from the webserver. Wouldnt is be great if there is some way we could only change part of the html?

this is what AJAX allows us to do.

AJAX stands for Asynchronous JavaScript and XML. The basic idea is this.

  • In the case of our example, the user clicks on a link to view a different news story. This click action is picked up with javascript , rather than a normal <a href=”"> style tag pointing to a different URL.
  • The javascript function then sends a HTTP request to the webserver for the information (i.e. the new news story). The webserver then sends back the news story to the web browser , generally in XML format.
  • The javascript then parses this javascript, and places the text of the story into the correct places. All the time through, the whole page is not reloaded, but instead only the news content area is changed by javascript.


This allows for far more eficiency, less bandwidth consumption, and also a far quicker loading time.

Example

Now, lets create a quick basic example, showing the power of AJAX.

In order to save us alot of time, we will not write a whole set of functions in javascript to get and send information to the webserver, instead we will use a AJAX libary called Prototype (www.prototypejs.org). This simplifies the task greatly.

The first step is to explain the setup we will use for this example.

  • We will start by having a HTML page, to display anews article (as above).
  • This will include some javascript to handle all AJAX functions.
  • Lastly we will have a PHP file to send the news articles to the client.

Step 1 : PHP File

First up is to create a PHP file to grab news files from our Mysql Database.

I’ll design a simple database table like this:

1
2
3
4
5
6
7
8
9
CREATE TABLE `news` (
`news_guid` int(255) NOT NULL AUTO_INCREMENT,
`news_title` varchar(255) NOT NULL,
`news_tagline` varchar(255) NOT NULL,
`news_body` varchar(255) NOT NULL,
`news_author` varchar(255) NOT NULL,
`news_date` varchar(255) NOT NULL,
PRIMARY KEY  (`news_guid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

255 character strings wont normally suffice for a real application, but are set this way to keep the sample application small.

Now with that created, we create a simple PHP script, to first loadup the database, and to query the database for the correct story.

We will place the story id as apart of the GET variables.. so we can have for example:

1
ourfile.php?storyid=1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// loadup db
$hDatabase = mysql_connect('your_host', 'your_usrn','your_pass');
mysql_select_db('your_db_name');
 
// lets assume that no hacker will be trying
// to break into our site, as this is just an example
// so i will not bother checking that the data input is
// a sql injection etc (see php security mistakes article)
$news_story_id = $_GET['storyid'];
 
//query the database
$dataset = mysql_query("SELECT * FROM news WHERE news_guid = '$news_story_id'", $hDatabase);
 
//check valid story number
if(mysql_num_rows($dataset) != 1)
{
 
//just show the first story
$dataset = mysql_query("SELECT * FROM news WHERE news_guid = '1'", $hDatabase);
 
}
 
$row = mysql_fetch_assoc($dataset);

This is all pretty simple, but what we want is the data to be output in XML format, for the javascript. Again, to save time, i have created an XML class to do this. (see included zip file for sourcecode).

If you havent met XML before, i suggest reading this as some basic background first.

we will now add in this code, to initialise and include the class:

1
2
3
4
require('xmlcreator.php');
 
// create XML object (see cmlcreator.php)
$xml = new XML_CREATOR();

With this class we will create a “Main News Element”, with attributes for the content, author, date etc. so eventually it will look like this:

1
2
3
4
5
6
The tagline goes here
 
The actual story goes here
 
the author goes here
the date goes here

Now, we will create this using the class by:

  • Running the begin() function
  • Creating the Main News Tag
  • Adding the body, author etc. attributes
  • Closing the News tag
  • running the end() function
1
2
3
4
5
6
7
8
9
10
//now, lets create the XML
$xml->begin();
$xml->addElement('news', '');
$xml->addAttribute('title', '',   $row['news_title'] );
$xml->addAttribute('tagline', '', $row['news_tagline']);
$xml->addAttribute('body', '',    $row['news_body']);
$xml->addAttribute('author', '',  $row['news_author']);
$xml->addAttribute('date', '',    $row['news_date']);
$xml->closeElement();
$xml->end();

Finally, we want the php page to output this xml:

1
2
//output XML
echo $xml-&gt;getXml();

Step 2 HTML & Javascript

Now its time to create our html page design.

For the way the javascript is wrote in this example.. make sure that:

  1. Area where title goes is a <p> tag with id title
  2. Area where taglines goes is a <p> tag with id tagline
  3. Area where date goes is a <p> tag with id date
  4. Area where story goes is a <p> tag with id body
  5. Area where autho goes is a <p> tag with id author

With this created, lets now make the javascript

As i said before, we’ll use the prototype libary for this…
For more information about its use, and to download it, visit their website:
(www.prototypejs.org).

We will first craete a file called index.js.
This will have a function called getstory whcih will simply run the code
to get the story from the php script, and then put it into the html

This will be run when the view story 1 etc. buttons are clicked

we’ll create a file index.js with the contents:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function getstory(form, id) {
 
var param = '';
 
var ParseFunc = function(t) {
 
var xmlDoc = t.responseXML.documentElement;
 
document.getElementById('author').innerHTML = xmlDoc.getElementsByTagName('author')[0].firstChild.data;
document.getElementById('date').innerHTML = xmlDoc.getElementsByTagName('date')[0].firstChild.data;
document.getElementById('title').innerHTML = xmlDoc.getElementsByTagName('title')[0].firstChild.data;
document.getElementById('tagline').innerHTML = xmlDoc.getElementsByTagName('tagline')[0].firstChild.data;
document.getElementById('body').innerHTML = xmlDoc.getElementsByTagName('body')[0].firstChild.data;
}
 
var Error = function(t) {
alert('Error 404: location "' + t.statusText + '" was not found.');
 
}
 
new Ajax.Request('getnews.php?storyid='+id,{onSuccess:ParseFunc, on404:Error, onFailure:Error});
 
}

Lets look at this in closer detail…

The getstory fiunction is defined as:

1
function getstory(form, id) {

and then several variables are defined……

1
2
3
var param = '';
var ParseFunc = function(t) {......}
var Error = function(t) {.......}

The param var is to hold any etra parameters for the AJAX function (again see prototype website for more info).

The parsefunc variable is a function, that parses the XML into our HTML page. looking at its definition:

1
var ParseFunc = function(t) {

The variable T is the XML data

The parsing ofXML and inserting into html here is created using a javascript feature called DOM please read this if you have not met it before.

The Error variable holdsa function that is run if the Ajax function does not run properly. Here, it just creates a popup menu.The finalpart of the code is the call to the AJAX function:

1
 new Ajax.Request('getnews.php?storyid='+id,{onSuccess:ParseFunc, on404:Error, onFailure:Error});

This simply gets the data from the url given to it, note that we’ve also included the story id as the variable id.

Putting it all together

The last step is to connect this javascript function to our html.

This is done by creating tags in the html , linking to other stories:

1
2
3
<a onclick="getstory(this,1);" href="#">Load Story 1</a>
<a onclick="getstory(this,2);" href="#">Load Story 2</a>
<a onclick="getstory(this,3);" href="#">Load Story 3</a>

And now were complete :)

Share and Enjoy:

  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Blogsvine
  • E-mail this story to a friend!
  • LinkedIn
  • Live
  • NewsVine
  • Print this article!
  • Reddit
  • Slashdot
  • Spurl
  • StumbleUpon
  • Technorati
  • YahooMyWeb

Tags: , , , ,

Leave a Reply