Ajax post data example

Here is a practical example of Ajax post data and how data is being communicated with php. Let's take an HTML form with two text field, name and comment.

exampleform.html
Code | Download
<html>
<head>
<title>Ajax post data example</title>
<script type="text/javascript" src="ajaxsubmit.js"></script>
</head>
<body>
<div id="feedback"></div>
<form name="frm" onsubmit="return(false)">
<table>
<tr><td>Your name (maximum 20 characters):</td><td><input name="name" type="text"></td></tr>
<tr><td>Comment (maximum 100 characters):</td><td><input name="comment" type="text"></td></tr>
<tr><td colspan="2"> <input name="Submit" type="button" value="Submit" onClick="submitForm(this)"></td></tr>
</table>
</form>
</body>
</html>

It is a simple HTML form code with one exception that the form is prevented from submission by using onsubmit="return(false)" inside the form tag. Another thing you can look that there is a blank division (id="feedback"). This division actually holds a place to display Ajax response.

JavaScript code:

Inside the JavaScript page (ajaxsubmit.js) there are following functions.
  • trim(str): This function is used to remove leading and trailing spaces of a string.
  • validateForm(frm): This function checks whether the data submitted according to the given guideline.
  • totalEncode(str): This function encode data before they submitted. As we know the JavaScript function escape(string) encode all characters except '+', '@', '*' and '/'. In this function I replace the every occurrence of such characters by their hex equivalent.
  • connect(): This function creates and returns an XML HTTP REQUEST object, upon failure display an error message.
  • submitForm(frm): This function is the heart of this JavaScript code. When user click on the submit button this function is called. This function serves four purposes.
    • Validate the form submitted by calling the function validateForm(str).
    • Create a new Ajax connection by calling connect().
    • Send encoded form data to the page formdata.php.
    • Display the response text from the server.
ajaxsubmit.js
Code | Download
function trim(str){
return str.replace(/^ss*/, '').replace(/ss*$/, '');}
function totalEncode(str){
var s=escape(trim(str));
s=s.replace(/+/g,"+");
s=s.replace(/@/g,"@");
s=s.replace(///g,"/");
s=s.replace(/*/g,"*");
return(s);
}
function connect(url,params)
{
var connection;  // The variable that makes Ajax possible!
try{// Opera 8.0+, Firefox, Safari
connection = new XMLHttpRequest();}
catch (e){// Internet Explorer Browsers
try{
connection = new ActiveXObject("Msxml2.XMLHTTP");}
catch (e){
try{
connection = new ActiveXObject("Microsoft.XMLHTTP");}
catch (e){// Something went wrong
return false;}}}
connection.open("POST", url, true);
connection.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
connection.setRequestHeader("Content-length", params.length);
connection.setRequestHeader("connection", "close");
connection.send(params);
return(connection);
}
function validateForm(frm){
var errors='';
var str=trim(document.frm.name.value);
if (str.length > 20){
errors+='post name must be within 20 characters.n'; }
var str=trim(document.frm.comment.value);
if (str.length > 100){
errors+='post name must be within 100 characters.n'; }

if (errors){
alert('The following error(s) occurred:n'+errors);
return false; }
return true;
}
function submitForm(frm){
if(validateForm(frm)){
document.getElementById('feedback').innerHTML='';
var url = "formdata.php";
var params = "name=" + totalEncode(document.frm.name.value ) + "&comment="+totalEncode(document.frm.comment.value );
var connection=connect(url,params);

connection.onreadystatechange = function(){
if(connection.readyState == 4){document.getElementById('feedback').innerHTML=connection.responseText;}
if((connection.readyState == 2)||(connection.readyState == 3)){document.getElementById('feedback').innerHTML = '<span style="color:green;">Sending request....</span>';}}}
}

Ajax PHP data communication:

At the server end the file formdata.php accepts and decodes submitted data from exampleform.html. After decoding it process them and give a response to the distance end.

formdata.php
Code | Download
<?php
$name=trim(addslashes(htmlspecialchars(rawurldecode($_POST["name"]))));
$comment=trim(addslashes(htmlspecialchars(rawurldecode($_POST["comment"]))));
if(empty($name)||empty($comment)){
echo '<font color="red">Please fill the form</font>';
exit;}
$comment=str_replace("n","<br>",$comment);
$data='Data submitted by '.$name.'<br><big>Comment:</big><br>'.$comment;
echo $comment;
?>
Comments:

cool

COMMENT BY: emmolos DATE: Aug 23, 22:07
I like your tutorials, is there anyway i could have it on my site?

Ajax post submit: Other HTML elements

COMMENT BY: jeet09 DATE: Sep 28, 12:11
Greate article. How to submit other html elements like radio button, checkbox and combobox in Ajax?
Method of PHP server response is also not very clear to me.

Post radio button, checkbox and combobox in Ajax

COMMENT BY: admin DATE: Sep 28, 12:13
I add one checkbox, a pair of radio button and a combobox in my example form. HTML code added will be
Code
<!-- Add checkbox -->
<tr><td>Remember me:</td><td><input type="checkbox" id="cb1" /></td></tr>
<!-- Add radio button -->
<tr><td>Male:</td><td><input name="gender" id="male" type="radio" /></td></tr>
<tr><td>Female:</td><td><input name="gender" id="female" type="radio" /></td></tr>
<!-- Add combobox -->
<tr><td>Select option:</td><td>
<select id="select_me" />
<option selected="selected" value="item1">Select item1</option>
<option value="item2">Select item2</option>
<option value="item3">Select item3</option>
</select></td></tr>
Now I re-write the JavaScript function submitForm():
Code
function submitForm(frm){
if(validateForm(frm)){
document.getElementById('feedback').innerHTML='';
var remember=(document.getElementById('cb1').checked);
var gender="male";
if(document.getElementById('female').checked){gender="female";}
var item=document.getElementById('select_me').value;
var url = "formdata.php";
var params = "name=" + totalEncode(frm.name.value ) + "&comment="+totalEncode(frm.comment.value ) + "&remember=" + remember+"&gender="+gender+"&item="+item;
var connection=connect(url,params);
connection.onreadystatechange = function(){
if(connection.readyState == 4){document.getElementById('feedback').innerHTML=connection.responseText;}
if((connection.readyState == 2)||(connection.readyState == 3)){document.getElementById('feedback').innerHTML = '<span style="color:green;">Sending request....</span>';}}}
}
PHP server response on AJAX POST Submit

Whenever the PHP code at the server end outputs some text, whether from a database or any other means, the JavaScript event "connection.onreadystatechange" fires. It is the responsibility of the programmer to utilize this event. The most general method of utilization of this event is to call a function which then does the necessary jobs. In this example I define a function which display the text output from the server.

XML HTTP REQUEST OBJECT readyState property

XML HTTP REQUEST OBJECT may have five readystate property, 0,1,2,3,4, each defining the state of server response. Whenever readyState property value changes the JavaScript event "connection.onreadystatechange" fires. The property value 4 define response from server has been completed. I use this property value to display the server response on the document.

No title

COMMENT BY: saiful DATE: Mar 28, 15:45
Hi,

I'm not sure what is wrong but I am pretty sure that I copy all the code correctly but still I cannot make the script working. Is there any demo site for me to refer? Please help.

make the script working

COMMENT BY: admin DATE: Mar 29, 08:11
Hello,
Do you keep all three files
  1. exampleform.html
  2. ajaxsubmit.js
  3. formdata.php
in same directory?
Do you save them as their extension?
If not then please do it and try again. If necessary you can give your page url where you try this example.
Thanks.

No title

COMMENT BY: saiful1 DATE: Mar 29, 14:10
Hi Admin,

Thanks for reply. I did naming all the files like what you wrote on your blog. I test using firefox nothing happen but if I try using explorer I get error on page (icon at the left bottom of explorer).
Here is the url http://essc.com.my/test/exampleform.html

Thanks again..

No title

COMMENT BY: admin DATE: Mar 29, 17:25
Hello,

There is a mistake in my HTML form code that I forget to add the name property of the HTML form. Now I have corrected it.

Moreover I like to mention that an HTML form is not essential for AJAX POST SUBMIT. In such case you have to retrieve the field data by common JavaScript function document.getElementById. Any way below I attach my sample code which I verify in IE and MOZILLA FIREFOX.
Download example code

No title

COMMENT BY: saiful1 DATE: Mar 30, 13:17
Thanks you for your kindness to correct the html. It is working now. I am in the process of learning the script (ajax & javascript).
I try to add the extra form that you wrote in the comment. but not working. I will try to find the problem.
Thanks again.

No title

COMMENT BY: golam DATE: May 12, 05:37
hi,
i have been trying it many way but after clicking the submit button output is
" Please fill the form'; exit;} $comment=str_replace("\n","
",$comment); $data='Data submitted by '.$name.'
Comment:
'.$comment; echo $comment; ?>"

ff ok but...

COMMENT BY: Gabole DATE: Aug 19, 18:01
Hello
thank you for this very good tutorial. it works like a charm on FF, but i can't get it to work with chrome, ie and opera.
chrome error is: Uncaught TypeError: Cannot read property 'name' of undefined
IE error is: SCRIPT5007: Impossible d%u2019obtenir la valeur de la propriété « name » : objet null ou non défini

somebody have any clue ?

thanks !

slight mistake

COMMENT BY: davecgs DATE: Sep 07, 14:10
You are using the form name (frm) as the parameter to the javascript code. However, you forget to enclose the name in quotes ('frm') in exampleform.html. Because of this the javascript only works because the name of the form (frm) is the same in both the javascript and the exampleform.html. Please correct that minor error in otherwise a great example. Thank you.

auto updating XML data without php and only with javascript

COMMENT BY: janardhan DATE: Jan 10, 08:10
Can't we do the auto updation of xml data without using php or any back end process and only by using javascript. please reply. Thanks in advance

Add comment