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<html> <head> <title>Ajax post data example</title> <script type="text/javascript" src="ajaxsubmit.js"></script> </head> <body> <div id="feedback"></div> <form 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.
function trim(str){
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');}
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(frm.name.value);
if (str.length > 20){
errors+='post name must be within 20 characters.\n'; }
var str=trim(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(frm.name.value ) + "&comment="+totalEncode(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>';}}}
}
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
<?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;
?>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.
I add one checkbox, a pair of radio button and a combobox in my example form. HTML code added will be
<!-- 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():
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>';}}}
}
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 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.
I like your tutorials, is there anyway i could have it on my site?