The “Hello World” AJAX script

I just made this quick ajax tutorial for people who’re starting out there and want to learn AJAX. The following tutorial will teach on how to submit a simple form through php and get the stuff printed out by using AJAX. The first sect will be plain simple to just print a input string and I’ll add getting some dynamic content after it.

So let’s get started.
For most of you you may have a local server at your PC or a remote hosting, remember there’re no special requirements for this tutorial all you need is a php installed server. If you’re right starting away you can install XAMPP which will install all defauly modules on your PC directly. I’ll be getting a good tutorial on this if I get enough requests.

Click below for continuing the tutorial ….


For the first part we’ll do our job using two files,

1) Index.php

2) ajax.js (The AJAX framework)

3) Style.css (stylesheet)

4) form.php (To process the submitted data)

So let’s first get started with ajax.js, I’ll explain this particular framework part by part.

We create a new file name “ajax” with “.js” extension.

Open up the file in your favourite text editor anf follow the instructions that follow.
We first create 4 new variables ->

var xml = makeXML();
var form;
var loading;
var results;

xml – for creating the xml request,
form – which gives the name of the form we’re going to use,
loading – The div tag where the “loading” message will appear.
results – The div tag where the output from the server will be shown.

Now let’s create a XMLHttpRequest object depending on the browser the user uses. Remember Firefox owns the world! So let’s add some couple of more lines to the code.. I’ll be explaining each part by adding the comment tags corresponding to the respective lines.

function makeXML () {
if (typeof XMLHttpRequest == ‘undefined’) { // CHECK FOR IE
objects = Array(
‘Microsoft.XmlHttp’,
‘MSXML2.XmlHttp’,
‘MSXML2.XmlHttp.3.0′,
‘MSXML2.XmlHttp.4.0′,
‘MSXML2.XmlHttp.5.0′
);
for (i = 0; i < objects.length; i++) {
try {
return new ActiveXObject(objects[i]); // CREATE ACTIVEX IF IE
} catch (e) {}
}
} else { // Else if other browser create their respective request.
return new XMLHttpRequest();
}
}

Now get’s the real part which has the vital information, but before that let’s see how does the current “ajax.js” file looks so far…

var xml = makeXML();
var form;
var loading;
var results;
function makeXML () {
if (typeof XMLHttpRequest == ‘undefined’) {
objects = Array(
‘Microsoft.XmlHttp’,
‘MSXML2.XmlHttp’,
‘MSXML2.XmlHttp.3.0′,
‘MSXML2.XmlHttp.4.0′,
‘MSXML2.XmlHttp.5.0′
);
for (i = 0; i < objects.length; i++) {
try {
return new ActiveXObject(objects[i]);
} catch (e) {}
}
} else {
return new XMLHttpRequest();
}
}

Ok Now We’ll be adding some more lines, this time I’ll break each of them so that you understand clearly.

window.onload = function () {
form = document.getElementById(‘form’);
loading = document.getElementById(‘loading’);
results = document.getElementById(‘results’);

Now let’s break it in parts and see how it works.

window.onload = function () { -> We load a function as soon as the page is called upon.

form = document.getElementById('form');
loading = document.getElementById('loading');
results = document.getElementById('results');

Remember the variables we declared at start ? now it’s time to give them some value.
we give form = document.getElementById(‘form’); which means to get the element names “form”.

Similarly loading and results are too stored.
Now let’s look further more.

form.onsubmit = function () {
results.style.display = ‘none’; // Set the Display STYLE of results to “none”
results.innerHTML = ”; // Fill up results with NULL (Nothing)
loading.style.display = ‘inline’; // Set the Display STYLE of loading to show up, so that whenever the user clicks a loading text/image shows up.

form.onsubmit = function () { -> When the form is submitted perform the function
results.style.display = ‘none’; -> Set the Display STYLE of results to “none”
results.innerHTML = ”; -> Fill up results with NULL (Nothing)

Now let’s proceed further.

xml.open(‘get’, ‘./form.php?name=’ + escape(this.name.value))

open the file through xml using header “get” that is form.php and we pass on the variables asked by the php file.

Observe carefully we call upon a file form.php which wants the data for it’s variable “name“.
We assign the value to the variable as “this.name.value“, notice something there ? the part in the middle “name” tells the javascript to give the value of form name which has ‘name’.

You maybe puzzled there, let me explain in plain words we give form.php to assign a value to the variable “name” with the form which has the id as “name” this may still be confusing but note this It’ll be cleared soon when we start the php form.

ok let’s go ahead and see the next few lines.

xml.onreadystatechange = function () {
if (xml.readyState == 4 && xml.status == 200) {

xml.onreadystatechange = function () { -> when the data is received perform the further action.

if (xml.readyState == 4 && xml.status == 200) { -> When ReadyState property is 4 and Status is 200, do the next stuff inside the loop.

Now you may ask me about these properties let’s see ->
Check W3′s clear explanation on these AJAX properties

Now when we have the positive response from the server let’s perform the main function.

results.style.display = ‘block’;
results.innerHTML = xml.responseText;
loading.style.display = ‘none’;
}
}

Let’s break ‘em too
results.style.display = ‘block’; -> Open up the results block
results.innerHTML = xml.responseText; -> Paste the SERVER’s response in the div tag results.
loading.style.display = ‘none’; -> Remember we set a loading tag on to display ? now when we got the data let’s switch of the loading stuff.

Now the last part of this nasty javascript…

xml.send(null); // if no data is sent, replace the results with NULL.
return false;
}
} // Loop closed.

OK AJAX.JS is complete, let me give you the complete code.

———————————————————————————-

http://hakc.net/ajax/ajax.js

There you go, hope I didn’t mess the stuff up yet.
Now let’s move over to the main PHP Stuff.

I’m converting the html to special chars, till then please refer the URL below.

Now the index.php will be done the code is here, remember to change the extension to .php

http://www.hakc.net/ajax/index.txt

——————————————————————————

now you maybe buzzing around that won’t the loading page displayed regardless of the user submits the form or not right ? That’s why we have linked a stylesheet into it. We’ll define a property to the “loading” tag which will hide the loading tag so that it’s not executed when the page is displayed, instead when teh user submits teh form the javascript OVERRIDES the stylesheet property and displays it again.

Lets look over at teh stylesheet.css

#loading {
display: none; // It’s pretty simple it just hides it!
}

Here is the stylesheet, again remember to change the extension to css.

http://www.hakc.net/ajax/stylesheet.txt

———————————————————————–

Now last but not the least let’s go with the last php file which processes the data and prints us out!

This is pretty simple!

<?php
$printdata=$_GET['name']; // Get the “name” data and store it in “printdata”.
echo $printdata; // print the stuff stored in printdata.
?>

Ok so there it goes the final stuff, the php code. (PS again change the ext to php)

http://www.hakc.net/ajax/form.txt

Ok so here I finish this sweet tutorials, remember to reply any comments/bugs/mistakes/improvements/feedbacks. Hope everyone liked this tutorial.

PS : Yeah this is again my biggest tutorials I’ve written yet!