Insert Data Using XMLHttpRequest

In conventional HTML+PHP website, the page would be redirected to other page when we submit data to server and in some case, this is not comfortable / effective way.

But, XMLHttpRequest already eliminates the redirect page process and exchange data with a server is happen in behind the scenes / current page. XMLHttpRequest can :
  • Update a web page without reloading the page
  • Request data from a server after the page has loaded  
  • Receive data from a server after the page has loaded
  • Send data to a server in the background
 For simple visualisation :


So, let's begin our tutorial. 

First, create a simple table in MySQL :
 CREATE TABLE IF NOT EXISTS `employee` (  
  `id` int(11) NOT NULL,  
  `name` varchar(60) NOT NULL,  
  `gender` varchar(12) NOT NULL,  
  `position` varchar(30) NOT NULL  
 ) ENGINE=InnoDB DEFAULT CHARSET=latin1;  


Create PHP file named conn.php for database connection :
 <?php  
 ini_set('display_errors',FALSE);  
 $host="<server_address>";  
 $user="<user>";  
 $pass="<password>";  
 $db="<database_name>";  
 $con=mysql_connect($host,$user,$pass);  
 mysql_select_db($db,$con);  
 if (!$con){  
      echo 'Can not be connected to Database Server!&nbsp;';   
 }  
 ?>  

Create a Javascript file named form.js for handle HTML form action :
 function getXmlHttpRequestObject() {  
   if (window.XMLHttpRequest) {  
     return new XMLHttpRequest();  
   } else if(window.ActiveXObject) {  
     return new ActiveXObject("Microsoft.XMLHTTP");  
   } else {  
     alert("Your Browser Sucks!");  
   }  
 }  
 //Our XmlHttpRequest object to get the auto suggest  
 var Req = getXmlHttpRequestObject();  
 function handle_submit() {  
   var name = document.getElementById("name").value;  
   var gender = document.getElementById("gender").value;
   var position = document.getElementById("position").value;
   var parameters = "name="+name+"&gender="+gender+"&position="+position;// Create parameters to be sent for server  
   Req.open("POST", 'data.php', true);  
   Req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");  
   Req.setRequestHeader("Content-length", parameters.length);  
   Req.setRequestHeader("Connection", "close");  
      Req.send(parameters); // Begin send the data  
   Req.onreadystatechange = function() { // Function to read server response  
           if (Req.readyState == 4) { // If server already executed the request  
                var str = Req.responseText.split("&nbsp;"); // Read string data that is sent from server  
                if (str[0] == 'success') {  
                     alert("Data inputted successfully.");  
                }else {  
                     alert(str[0]);  
                }  
           }  
      }  
 }  

Create HTML form named index.html :
 <html>  
  <head>  
       <meta charset="utf-8">  
       <meta name="viewport" content="width=device-width, initial-scale=1.0">  
       <title>Example Submit Data</title>  
       <script src="form.js"></script>  
   </head>  
   <body>  
           <form>  
           <label>Name :</label><input type="text" id="name" />  
           <br /><label>Gender :</label><select id="gender"><option value="Male">Male</option><option value="Female">Female</option></select>  
           <br /><label>Position :</label><input type="text" id="position" />  
           <br />  
           <br />  
           <button type="button" onclick="handle_submit()">Submit</button>  
           </form>  
   </body>  
 </html>  

Last, create PHP file named data.php :
 <?php  
 include "conn.php";  
 $name = $_POST['name'];  
 $gender = $_POST['gender'];  
 $position = $_POST['position'];  
 mysql_query("INSERT INTO `employee` VALUES ('NULL','$name','$gender','$position')");  
 if (!mysql_error()) {  
      echo 'success&nbsp;';  
 }else {  
      echo mysql_error()."&nbsp;";  
 }  
 ?>  

Just type your data and your data will be inputted in behind the page. This example is very simple and you can improvise with your own code like edit data, delete data, and even display the data table.

You could download the source code from this below link :
https://drive.google.com/file/d/0B0eiI_3d7A65amdTQWF3ZjlzakE/view

Comments