You Are Here Home > AJAX – Beginner AJAX Tutorial

AJAX – Beginner AJAX Tutorial

We are closing down our forums, it’s time to move on, but we are keeping some important threads, here are the AJAX tutorials…

AJAX – Beginner AJAX Tutorial

What you need to know
A basic knowledge of HTML, JavaScript and a server side language.

What is AJAX?
AJAX stands for Asynchronous JavaScript And XML.

XML?!
Don’t worry you don’t need to know XML, in fact we won’t even use XML to write web applications with AJAX.

What data type we will use you are going to see in later tutorials, but I assure you we will use
something 100 times simpler.

Overview
There are a few benefits you can gain by using this technique, one is than you won’t need to send the common parts of the page to the browser whenever a user views a page on your website.

Since this is a beginner AJAX tutorial let’s make a very simple ‘Hello World’ AJAX application.

Step 1:
We are going to use Yahoo! UI library or ‘yui’.
The benefit of using yui is that you don’t need to worry about browser compatibility and also many developers are working on it to make it even better every day.

So go ahead and download the latest version here:
http://developer.yahoo.com/yui/download/

Step 2:
Extract the files and in the ‘build’ folder you will see many folders containing different parts of yui.

For this tutorial we only need yahoo.js, event.js and connection.js
So go ahead and make an HTML file and call it ajax.html (or whatever you want).

Now paste this code into your HTML file:

<html>
<head>
<title>Beginner AJAX Tutorial</title>
 
<script type="text/javascript" src="edit this path to yui/yahoo.js"> </script>
<script type="text/javascript" src="edit this path to yui/event.js"> </script>
<script type="text/javascript" src="edit this path to yui/connection.js"> </script>
 
</head>
<body>
<div id="content">
</div>
</body>
</html>

2 notes:
1. You must edit the path to yui library and be sure the source attribute of your script tags point to the right files.
2. I also added a div to the page so we can display the server’s response in it.

Now we included the portions of yui that we need in our page so let’s write some code.

Step 3:
Now we need to write some code to use yui’s connection object to send requests to the server.

To do this we need to write 2 JavaScript functions to handle 2 situations.
1. Success.
2. Failure, most likely the server didn’t respond.

So lets write our functions, first success:

function success_handler(o) {
document.getElementById('content').innerHTML = o.responseText;
}

The only thing this function does is that it sets the innerHTML of our content container.

2 notes:
1. innerHTML is a non standard attribute that almost all the browsers support.
2. o is an object yui will pass to your functions.

Now lets make our failure handler:

function failure_handler(o) {
document.getElementById('content').innerHTML = 'Server or your connection is death';
}

Here again we change the innerHTML with an appropriate error message.

So all together we have:

<html>
<head>
<title>Beginner AJAX Tutorial</title>
 
<script type="text/javascript" src="yahoo.js"> </script>
<script type="text/javascript" src="event.js"> </script>
<script type="text/javascript" src="connection.js"> </script>
 
<script type="text/javascript">
function success_handler(o) {
document.getElementById('content').innerHTML = o.responseText;
}
 
function failure_handler(o) {
document.getElementById('content').innerHTML = 'Server or your connection is dead';
}
</script>
 
</head>
<body>
<div id="content">
</div>
</body>
</html>

Let’s go ahead and write two more functions, one for sending a request to the server and one for trying the failure situation.

Here we go:

function send_request() {
var callback = { success:success_handler, failure:failure_handler, timeout: 10000 };
YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/beginner-ajax-tutorial.php', callback);
}

This is a simple function that sends an asynchronous request to the server.

Let’s take a look at it in more detail:

1. We defined a callback object which sets our success_handler and failure_handler functions for success and failure situations respectively
and also we define a timeout for the connection. This timeout is in milliseconds, so we are setting it to 10 seconds.
This means if we receive a response within 10 seconds then yui calls our success_handler function, otherwise it calls failure_handler.

2. The second line is the actual request. asyncRequest method will handle everything and calls our callback functions.
We are passing 3 parameters.

First parameter is the type of request, which is GET here because we are not sending any form data to the server. (I will show you POST requests in later tutorials)

Second parameter is the URL which we want to send the request to.

Third parameter is our callback object.

Now let’s make another function to test the failure situation:

function test_failure() {
var callback = { success:success_handler, failure:failure_handler, timeout: 10000 };
YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/some-file-that-doesnt-exists.php', callback);
}

This function is the same except it sends a request to a non-existing file, so it’s going to fail.

So far we have this:

<html>
<head>
<title>Beginner AJAX Tutorial</title>
 
<script type="text/javascript" src="yahoo.js"> </script>
<script type="text/javascript" src="event.js"> </script>
<script type="text/javascript" src="connection.js"> </script>
 
<script type="text/javascript">
function success_handler(o) {
document.getElementById('content').innerHTML = o.responseText;
}
 
function failure_handler(o) {
document.getElementById('content').innerHTML = 'Server or your connection is death';
}
 
function send_request() {
var callback = { success:success_handler, failure:failure_handler, timeout: 10000 };
YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/beginner-ajax-tutorial.php', callback);
}
 
function test_failure() {
var callback = { success:success_handler, failure:failure_handler, timeout: 10000 };
YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/some-file-that-doesnt-exists.php', callback);
}
</script>
 
</head>
<body>
<a href="javascript:send_request();">Send Request</a> | <a href="javascript:test_failure();">Fail a request</a>
<div id="content">
</div>
</body>
</html>

Note: I added the line:

<a href="javascript:send_request();">Send Request</a> | <a href="javascript:test_failure();">Fail a request</a>

To be able to test our little application.

Go ahead and try it here:

http://images.code-head.com/tutorials/ajax/beginner-ajax-tutorial.html

And the PHP file is only 3 lines:

<?php
echo 'Hello World!';
?>

That’s it for now.
Thanks and good luck!
-Codehead

Next: AJAX – Beginner AJAX Tutorial – Display a Progress Bar or a Loading Message

AJAX – Beginner AJAX Tutorial
Filed under: AJAX, JavaScript, PHP, Web Development, yui   Posted by: Codehead on January 21, 2010

Disclaimer
1 - Use the information provided here at your own risk.
2 - You may not republish this content without prior written consent.




6 Comments »

  1. Baptiste:
     

    Hello,

    When i click on “Send request” or “Fail a request”, i have “Server or your connection is death”, why ?
    Thanks you per advance,

    Baptiste.

    Comment — February 1, 2010 @ 5:01 pm

  2. Codehead:
     

    Did you modify this code by any chance? If so, please post your code here…

    Comment — February 1, 2010 @ 5:04 pm

  3. Baptiste:
     

    No i didn’t modify this code. It’s the basic code demo :

    Beginner AJAX Tutorial – Progress Bar

    function success_handler(o) {
    replace_html(‘content’, o.responseText);
    }

    function failure_handler(o) {
    replace_html(‘content’, ‘Server or your connection is death’);
    }

    function replace_html(id, content) {
    document.getElementById(id).innerHTML = content;
    }

    function show_progressbar(id) {
    replace_html(id, ”);
    }

    function send_request() {
    show_progressbar(‘content’);
    var callback = { success:success_handler, failure:failure_handler, timeout: 10000 };
    YAHOO.util.Connect.asyncRequest(‘GET’, ‘http://images.code-head.com/tutorials/ajax/beginner-ajax-tutorial.php’, callback);
    }

    function test_failure() {
    show_progressbar(‘content’);
    var callback = { success:success_handler, failure:failure_handler, timeout: 10000 };
    YAHOO.util.Connect.asyncRequest(‘GET’, ‘http://images.code-head.com/tutorials/ajax/some-file-that-doesnt-exists.php’, callback);
    }

    var progress_bar = new Image();
    progress_bar.src = ‘http://images.code-head.com/progress-bars/4.gif’;

    Comment — February 1, 2010 @ 5:09 pm

  4. Codehead:
     

    Are you using a firewall?

    Some firewalls block AJAX…

    Comment — February 1, 2010 @ 5:37 pm

  5. Baptiste:
     

    No i don’t use firewall.

    I put the timeout to 20000 and it is good !

    Comment — February 1, 2010 @ 5:52 pm

  6. Codehead:
     

    Great!

    Are you on a dial-up connection? Because the timeout is already 10 seconds…

    I’m glad you figured it out :)

    Comment — February 1, 2010 @ 6:22 pm

RSS feed for comments on this post. TrackBack URL

Leave a comment