TECHNOlogy: What is AJAX? Baby Don’t Hurt Me!

Wikipedia defines AJAX (Asynchronous JavaScript And XML) as:

A group of interrelated web development techniques used on the client-side to create asynchronous web applications.

What a mind-numbing description! What you need to know is that AJAX is the combination of a several technologies to make better web pages.

If you have no interest in making websites but you like techno music, or you’re curious why I picked that title, this is for you:

http://www.youtube.com/watch?v=Xk_XaJ7gE4Q
This is a good soundtrack for this post. You should hit play and keep reading.

After a bit of time with HTML/CSS I started to build a growing list of issues that I couldn’t solve without some scripting.

I learned some PHP, which wasn’t tricky because it uses very common concepts. Here’s the traditional ‘hello world’ example in PHP:

<?PHP echo ‘Hello World’; ?> = Hello World

.. and if I wanted to be a bit more dynamic:

<?PHP echo ‘Hello World it is ‘.date(‘Y’); ?> = Hello World it is 2012

Because PHP is only run when the page is requested, and only runs on the server side, it’s only the server that loads/understands PHP; The browser does nothing with PHP.

With PHP code only seen by the server, it’s a very safe way to make your pages more intelligent without giving Google or other search engines a reason to be suspicious of your site.

In fact one of the most common applications of PHP for an SEO is something as simple as keeping your Copyright date current:

<?PHP echo ‘Copyright© 2004-‘.date(‘Y’); ?> = Copyright© 2004-2012

Plus when I need to store some information, or fetch that information, PHP isn’t that easy, so I added MySQL to the mix and suddenly my data nightmares are all data dreams and fairy tales (well almost). I won’t dive into MySQL on top of everything here, but lets just say that when you have a ton of data, you want easy access to it, and most ‘flat’ formats are far from the ease of MySQL.

But I still had a long list of things I couldn’t do that I knew I should be able to do.

The biggest problem I had was that all my pages had to ‘post’ something, figure out what I’d posted, and then re-load the page with updated information based on what was posted.

Picture playing a game of chess where you are drawing the board with pen and paper. Each move would be a fresh sheet of paper with the moved piece drawn over a different square.

PHP can get the job done, but it’s not a very smart way to proceed when you want to make an update to the current page vs. re-drawing the whole page.

So I learned some JavaScript, starting with the basic ‘hello world’ example:
<span onClick=”alert(‘Hello World’);”>Click</span>

hello world javascript alert box

If I wanted to see the date I’d have to add some more JavaScript:
<script language=”javascript”>
function helloworld()
{
var d = new Date();
alert(‘Hello World it is ‘ + d.getFullYear());
}
</script>

<span onClick=”helloworld();”>Click

Hello World it's 2012 alert box example

JavaScript is ONLY run on the browser, the server has no bearing on JavaScript, so the example above won’t always work as expected because it’s telling you the date on your computer, not on the server. How would we see the date of the server?

This is where AJAX comes into play. If we can tell the browser to invisibly fetch a page from a server and process the information that comes back, then we can combine the abilities of JavaScript, PHP, and MySQL.

Lets do the ‘hello world’ example with AJAX using the examples above.

First you would create the PHP file that does the server work as something witty like ‘ajax-helloworld.php’:
<?php echo ‘Hello World it is ‘.date(‘Y’); ?>

..next you’d create an AJAX function inside the web page you are working on:
<script language=”javascript”>
function helloworld()
{
var ajaxData; // Initialize the ‘ajaxData’ variable then try to set it to hold the request (on error, assume IE)
try{
// Opera 8.0+, Firefox, Safari
ajaxData = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxData = new ActiveXObject(“Msxml2.XMLHTTP”);
} catch (e) {
try{
ajaxData = new ActiveXObject(“Microsoft.XMLHTTP”);
} catch (e){
// Something went wrong
alert(“Your browser broke!”);
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxData.onreadystatechange = function(){
if(ajaxData.readyState == 4){
alert(ajaxData.responseText);
}
}
ajaxData.open(“GET”, “ajax-helloworld.php”, true);
ajaxData.send();
}
</script>

Only the purple text is customized, the rest of the function is a well established method of running an AJAX request that you should not need to edit.

So we have a function that loads the ‘ajax-helloworld.php’ page we made and then does an alert with the output of the page, all we have to do is put something on the page to call the function like that span example with the onClick=’helloworld();’ property.

Well that’s all neat but what about the ‘X’ in AJAX?

XML is a great thing because it’s a language that helps us with extensible mark-up of our data.

In other words XML is like a segregated serving dish for pickled food that keeps the olives from mixing with the beets.

Going back to our ‘hello world’ example we could look at the ‘date data’ and the ‘message data’ as objects:
<XML>
<message>Hello World it is</message>
<date>2012</date>
</XML>

Now, when the AJAX loads our ‘ajax-helloworld.php’ and gets an XML response we can tell what part of the response is the date, and which part is the message. If we made a new page that just needs to display the server’s date, we could re-use our example and only look at the ‘date’ object.

For some odd reason, most coders like JSON a lot, and this makes it really common to see AJAX using JSON vs. XML to package a data response. Here’s our XML example as a JSON string:
{“message”:”Hello World it is”,”date”:”2012″}

Not only is it really easy to read JSON, because JavaScript and PHP both understand JSON encoding it’s really easy to upgrade our ‘hello world’ XML example over to JSON format.

Here’s the new PHP command file ‘ajax-helloworld.php’:
<?php
$response = array(“message” => “Hello World it is”, “date” => date(‘Y’));
echo json_encode($response);
?>

The output of our AJAX PHP file will now be the same as the JSON example string. All we have to do is tell JavaScript to decode the response.

If you look back at this line from the AJAX JavaScript function example above:

if(ajaxData.readyState == 4){
alert(ajaxData.responseText);
}

This is where we’re handling the response from the AJAX request. So this is where we want to decode the response:

if(ajaxData.readyState == 4){
var reply = JSON.parse(ajaxRequestAT.responseText);
alert(‘The message is : ‘ + reply.message + ‘ and the date is : ‘ + reply.date);
}

Now we are asking for data, getting it back as objects, and updating the page with the response data objects.

If this example opened some doors for your website needs you really should continue to learn more. While the web is full of examples like this, from my personal experience I can honestly tell you that you’ll find yourself always trying to bridge knowledge gaps without a solid lesson plan.

Educational sites like LearnQuest, have excellent tutorials and lessons on AJAX and JavaScript including advanced topics like external AJAX with sites like Google and Yahoo. Plus LearnQuest also has jQuery tutorials that will help you tap into advanced JavaScript functionality without getting your hands dirty.

*Savvy readers will note that I gave PHP my blessings for SEO uses but said nothing of JavaScript’s impact on crawlers/search engines.

Kyle recently posted an article on GoogleBot’s handling of AJAX/JavaScript which digs into that topic a bit more.

With any luck I’ll get some time soon to share a gem of JavaScripting that allows you to completely sculpt your page-rank and trust flow in completely non-organic way. The concept would please search engines, but at the same time cannot be viewed as ‘white hat’ no matter how well it works.