Site Moved

This site has been moved to a new location - Bin-Blog. All new post will appear at the new location.

Bin-Blog

Ajax Feedback Form (Part 3 of the Ajax Tutorial)

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) inside the body part is not a good practice.

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. For that I will use my 'jx' ajax functions. This is the simpilest library - just 50 lines of code. This library has its limitations but for the present application it will do. There are many other Ajax libraries available in the net.

We need a new javascript file with the name 'jx_lib.js' with the following content...


/////////////////////////////////// ax Ajax Library Functions /////////////////////////////////
var jx_http = jx_getHTTPObject(); // We create the HTTP Object
//Create a xmlHttpRequest object - this is the constructor. 
function jx_getHTTPObject() {
 var xmlhttp;

 //Use IE's ActiveX items to load the file.
 if(typeof ActiveXObject != 'undefined') {
  try {
   xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
   try {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (E) {
    xmlhttp = false;
   }
  }
 //If ActiveX is not available, use the XMLHttpRequest of Firefox/Mozilla etc. to load the document.
 } else if (XMLHttpRequest) {
  try {
   xmlhttp = new XMLHttpRequest();
  } catch (e) {
   xmlhttp = false;
  }
 } else {
  xmlhttp = false;
 }
 return xmlhttp;
}

//This function is called from the user's script. It will take a url and an optional callback function.
// Then it will read the url file, expecting a json string. Once the file is loaded, the script
// will pharse the json string using 'eval' and call the user defined callback function with this
// array as the argument.
//Arguments - 
// url - The url of the serverside script that is to be called. Append all the arguments to 
//   this urls as GET params - like get_data.php?id=5&car=benz
// callback - Name of the function that should be called once the data is ready. If a callback
//   function is not given, then the default function 'jx_processResults' will be used.
function jx_getData(url,callback) {
 if(!jx_http) return;

 jx_http.open("GET", url, true); 

 //Call a anonymos function when the state changes.
 jx_http.onreadystatechange = function () {
  if (jx_http.readyState == 4) {//Ready State will be 4 when the document is loaded.
   var result;
   if(jx_http.responseText) result = eval(jx_http.responseText); //Yes, I know I used eval - its JSON, stupid.
   else result = "";

   if(callback) {
    callback(result); //Give the data to the user defined function.
   } else { //If there is no user defined function...
    //Call a predifined  function with the result.
    if(jx_processResults) jx_processResults(result);
   }
  }
 }
 jx_http.send(null);
}

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


<script language="javascript" type="text/javascript" src="jx_lib.js"></script>
<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() {
 if(jx_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>

The first line will include the ajax library functions. Don't worry about what the code will do - we will see more about it latter. 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.


//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.
 jx_getData("save_data.php?comment=" + comment + "&email=" + email + "&return=none");
 
 //Display the thank you message.
 document.getElementById("form_elements").innerHTML = "<h1>Feedback Recived</h1>Thank you for your intrest - we will look into your comment as soon as possible.";
 
 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'] == 'none') 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.

3 Comments:

Andy Haveland-Robinson said...

Please, always use safe practices such as this even with simple demonstrations.
Always clean what you eat!

$email=isset($_REQUEST[email]):$_REQUEST[email]:"";
$comment=isset($_REQUEST[comment])?$_REQUEST[comment]:"";

//Insert data into our database
$query = sprintf("INSERT INTO feedback(feedback_email,feedback_comment,feedback_time) VALUES('%s','%s',NOW())",
mysql_real_escape_string($email),
mysql_real_escape_string($comment));

mysql_query($query) or die("Cannot save : " . mysql_error());

Anonymous said...

I'm getting an error while implementing this. I assume I'm supposed to remove save_data.php from the form action="save_data.php" method="POST", so once I removed the save_data.php from the forms action, I get an error stating the the Method "GET" is not allowed and then it gives me the full path of the html file. Can you please take a look at my webpage for this located at: http://graphicsmayhem.com/subdomains/acs/ajax/ajax.html
Thank You!

Binny V A said...

One problem I can see is that the <script> tag was not closed - it should be...
<script language="javascript" type="text/javascript" src="jx_lib.js">
</script>

But I am not sure why you got that 405 error - that must be due to a server configuration issue.