Previous
Traditional Feedback Form 
Next
Ajax Library Explained 
A Gentle Introduction to Ajax
Ajax Feedback Form

Ajax Feedback Form

In this section we will add ajax functionality to the form we created in the last page. We will try to avoid touching the orginal code as much as possible - using behaviour elements(script) in side the body is not a good practice.

Form Submit Event

First we will create a new submit behaviour for the form. By default, the form will submit the data to a different page. We need to change this behaviour so that when the form is submited, a javascript function will be called.


<script language="javascript" type="text/javascript">
//This function will be called when the form is submited
function saveData() {
    // ...

    return false;//Prevent the form from being submited
}
function init() {
    document.getElementById("feedback_form").onsubmit = saveData; //The saveData function is attached to the submi action of the form. 
}
window.onload = init; //The 'init' function will be called when the page is loaded.
</script>

Put this code in the head part of the page. Now nothing will happen when you click the submit button. JavaScript will call the saveData() function - but since it does nothing, the user will not see any change in the page if the submit button is clicked. The return false; will prevent the form from being submited. The next step is to add the Ajax functionality to our page. There are many libraries available to this for your. I have created a small jx library for ajax. There are many other Ajax libraries available in the net. Some of the most popular ones are given in the Appendix section. But for the sake of the tutorial we will create the Ajax functionality by hand.

Adding Ajax Functionality - XMLHttpRequest

In our HTML file(the file containing the Feedback form, put the following code in the head section.


<script type="text/javascript">
function XMLHTTPObject() {
    var xmlhttp=false;
    //If XMLHTTPReques is available
    if (XMLHttpRequest) {
        try {xmlhttp = new XMLHttpRequest();}
        catch(e) {xmlhttp = false;}
    } else if(typeof ActiveXObject != 'undefined') {
	//Use IE's ActiveX items to load the file.
        try {xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");} 
        catch(e) {
            try {xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
            catch(E) {xmlhttp = false;}
        }
    } else  {
        xmlhttp = false; //Browser don't support Ajax
    }
    return xmlhttp;
}
var http = new XMLHTTPObject();


//This function will be called when the form is submited
function saveData() {
    // ...

    return false;//Prevent the form from being submited
}
function init() {
    if(http) {//If the browser supports Ajax functions
        document.getElementById("feedback_form").onsubmit = saveData; //The saveData function is attached to the submit action of the form.
    }
}
window.onload = init; //The 'init' function will be called when the page is loaded.
</script>

Don't worry about what the code will do - we will see that in detail later. Just include the code in our page. This will add the necessary ajax functionality to our page - now we must define what must happen when the user clicks the 'Submit' button. Just put the following code inside the 'saveData()' function.

Sending and Reciving Data using Ajax


//This function will be called when the form is submited
function saveData() {
    var comment = document.getElementById("comment").value;
    var email = document.getElementById("email").value;

    //By calling this file, we have saved the data.
    http.open("GET","save_data.php?comment=" + comment + "&email=" + email + "&return=confirm",true);
    
    http.onreadystatechange = function() {
        if(http.readyState == 4) {
            if(http.status == 200) {
                var result = http.responseText;
                var msg = ""
                if(result == '1') {
                    //Display the thank you message.
                    msg = "Thank you for your interest - we will look into your comment as soon as possible.";
                } else {
                    msg = "There was an error in inserting the record : " . result;
                }
                document.getElementById("form_elements").innerHTML = msg;
            }
        }
    }
    http.send(null);
    
    return false;//Prevent the form from being submited
}

This will pass the data to the 'save_data.php' PHP file that will insert the values into the database. The code used in the php file must be changed a bit to accomodate this. In the traditional way, the PHP will print out a thank you message - but in the Ajax method we do not need this. So we will have to disable this in ajax mode. Notice the argument &return=none in the line
jx.getData("save_data.php?comment=" + comment + "&email=" + email + "&return=none");

We will check for this argument in the PHP file - if we find this argument present, we will return without displaying anything. Else we will show the full thank you note. For this effect we will modify the PHP file thus...


<?php
include('./connect.php'); //Connect to the database.

//Insert data into our database
mysql_query("INSERT INTO feedback(feedback_email,feedback_comment,feedback_time) 
    VALUES('$_REQUEST[email]','$_REQUEST[comment]',NOW())") or die("Cannot save : " . mysql_error());

if($_REQUEST['return'] == 'confirm') {
    print 1;//Print a 1 to show that the insert worked.
    exit; //Exit without printing the Thank you note.
}

?>
<html>
<head>
<title>Feedback Recived</title>
</head>
<body>
<h1>Feedback Recived</h1>

Thank you for your intrest - we will look into your comment as soon as possible.

</body>
</html>

We are done. Now the Ajax Feedback form is fully functional. If the user's browser has JavaScript capability, the user will experiance the full effect of ajax. If they are using an old browser, our progam will still work - but in the traditional way - without any bells and whistles.

Explaination of the Code

Let see what happend line by line.

    var comment = document.getElementById("comment").value;
    var email = document.getElementById("email").value;

Very clear - take the value of the comment and the email fields to two variables with the same name.

open() Function

    //By calling this file, we have saved the data.
    http.open("GET","save_data.php?comment=" + comment + "&email=" + email + "&return=none",true);

Here, we are opening the connection to the server side scirpt using the XMLHTTPRequest object. We used the open() function. The three arguments for this function are...

Method
GET, POST or HEAD. This argument specify which method must be used in transporting the given data to the new file. Using the GET method, we will be able to pass the data to the server side script in the url itself - like this url.php?data=value. The POST method will send the data after the connection is opened. The HEAD method can be used to get the headers of the url without having to download the entire page. The method can be specified as the fourth argument of the load function in jx.
URL
The URL of the file that must be opened - the location of the server side script. This can be a absolute URL like(http://www.openjs.com/feedback.php) or a relative one(../../feedback.php). A note of caution - this URL should be in the same domain as the script is. You cannot call a script in google.com from a script that is running in yahoo.com. This is a security measure implemented in most browsers to prevent XSS.
Asynchronous/Synchronous
This argument will be true if the request is asynchronous and false if it is synchronous. If it is Synchronous, the browser will suspend all activity till the response is received. This causes firefox to freeze up. Asynchronous requests don't have this problem - they will download the new page in the background - allowing the user to do other things.

readyState


        http.onreadystatechange = function() {

The XMLHTTPRequest object has a property called the readyState. It changes its value reflecting various states of the Ajax request. We will set a function that will be called whenever the value of this 'readyState' changes. It can have 5 values...

http.readyState == 0
The request is not initialized (This is the state it has before you've called the open() function).
1
The request is ready, but not sent - when you have called open() but before you've called send()(We will call this function later).
2
The request was sent at this point - the headers of the response are usually available now.
3
The browser is downloading the requested data - headers and the some partial data may be available, but the server isn't finished with its response.
4
The download is complete - now you can receive and use the response.

As you see, the value '4' is the only one we are intrested in.


            if (http.readyState == 4) {//Ready State will be 4 when the document is loaded.

We check wether the readyState is 4 - continue only if the ready state is 4.


                if (http.status == 200) {

Check the response status - this will be 200 for all proper responses. If we get a file not found error, we will get 404 as the status. See the HTTP specification to find about other status codes.

responseText


                    var result = http.responseText;

Get the response into a variable called result as a string. This is the contents printed by the server side script.

Previous
Traditional Feedback Form 
Next
Ajax Library Explained 
blog comments powered by Disqus