Submit a form data using PHP, AJAX and Javascript

Theory of Computation
In this article, you will learn how to submit a form data without refreshing the web page using PHP, Ajax and Javascript. Generally, we have all seen that when we submit some form or fetch some records, the page refreshing or reloading may take some time. We can do the same process without refreshing the web page using Ajax.
Ajax is a technique to provide fast and dynamic web services. It updates or retrieves data asynchronously by exchanging data over the server. It has the ability to perform tasks on a web page without page refresh. 
To store the form data in the back-end, we must have a database. In this article, we have used the MySQL database. So, let's first create a database name Company in MySQL and a table name employee using the following MySQL statement. You can either use your existing database or copy paste the following command in your database.

CREATE TABLE IF NOT EXISTS `employee` (
  `emp_id` int(11) NOT NULL AUTO_INCREMENT,
  `emp_name` varchar(50) NOT NULL,
  `email` varchar(50) NOT NULL,
  `phone` int(11) NOT NULL,
  `address` varchar(50) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL,
  PRIMARY KEY (`emp_id`)
)

Next, create a simple form 'employee_form.php' to get information from employee.  This form contains all the fields that the employee table has. In this, we have included jQuery and Bootstrap libraries. 

<!DOCTYPE html>
<html>
 <head>
  <title>Submit Form Using AJAX, PHP and javascript</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
  <link href="style.css" rel="stylesheet">   <script type="text/javascript" src="formscript.js"></script>
 </head>
 <body>
  <form id="emp_form" name="form">
  <h3>New Employee Registration Form</h3>
  <div>
  <label>Employee Name* :</label> 
  <input type="text" name="emp_name" id="emp_name" />
  <label>Email* :</label>  
  <input type="text" name="email" id="email" />
  <label>Phone :</label>  
  <input type="text" name="phone" id="phone"  />
  <label>Address :</label>  
  <input type="text" name="address" id="address"  />
  <label>Username* :</label>  
  <input type="text" name="username" id="username" />
  <label>Password* : </label>  
  <input type="password" name="password" id="password"  />  <label>  </label>  
  <input id="submit" class="submit" onclick="formsubmit()" type="button" value="Submit">
  </div>
  </form>
  <div id="clear"></div>
</body>
</html>

The above file includes a css file name style.css and a javascript file name formscript.js. On click the submit button, formsubmit() method will be called which is defined in formscript.js file. 
The style.css file contains basic styles of the form.

#emp_form{
   width: 320px;
   height: 300px; 
   border: 2px solid #4AD1E2;
   padding: 10px;
   margin-left:auto;
   margin-right: auto;
   font-family: sans-serif;
}
label
{
    width: 150px;
    float: left;
    margin-right: 0.5em;
    display: block;
    margin-bottom: 7px;    
}
input
{
    color: #781351;
    background: #A2E7F0;
    border: 2px solid #4AD1E2;
    margin-bottom: 7px;  
}
.submit
{
   color: #000;
   background: #A2E7F0;
   border: 2px outset #4AD1E2;
   font-weight: bold;
} 
#clear{clear:both; }

The formscript.js file contains validation code and the else part of this code contains ajax codes which send the request to the PHP script with the form data and returns notification of a successful data submission. It sends the request without reloading the form.

function formsubmit() {
    var empname = document.getElementById('emp_name').value;
    var email = document.getElementById('email').value;
    var phone = document.getElementById('phone').value;
    var address = document.getElementById('address').value;
    var username = document.getElementById('username').value;
    var pwd = document.getElementById('password').value;
    //store all the submitted data in astring.
    var formdata = 'empname=' + empname + '&emailid=' + email + '&phn=' + phone + '&address=' + address +'&uname=' + username+ '&password=' + pwd;
	// validate the form input
	if (empname == '' ) {
		alert("Please Enter Employee Name");
		return false;
	}
	if(email == '') {
		alert("Please Enter Email id");
		return false;
	}
	if(username == '') {
		alert("Please Enter Username");
		return false;
	}
	if(pwd == '') {
		alert("Please Enter Password");
		return false;
	}
	else {
	// AJAX code to submit form.
	$.ajax({
		 type: "POST",
		 url: "storeempdata.php", //call storeemdata.php to store form data
		 data: formdata,
		 cache: false,
		 success: function(html) {
		  alert(html);
		 }
	});
	}
	return false;
}

In the above code, ajax code calls the storeemdata.php file to store the form data. Generally, we would send data to a server using POST request, the server handles it and sends a response back to the front-end. Instead of this, we have established the back-end connection here and captured the form data using Javascript and then, send an asynchronous request to the server for handling the response. We have used the improved version of MySQL, make sure to replace database credentials from yours. 
<?php
$name = $_POST['empname'];
$email = $_POST['emailid'];
$phn = $_POST['phn'];
$address = $_POST['address'];
$uname = $_POST['uname'];
$password = $_POST['password'];

// Establishing Connection with Server..
$conn = new mysqli('localhost', 'root', '', 'company');

//Check for connection error
if($conn->connect_error){
  die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error);    
}
// Selecting Database
$db = mysql_select_db("company", $connection); // Selecting Database

if (isset($_POST['empname'])) {

//Insert Query
$insert= "insert into employee(emp_id, emp_name , email, phone, address, username, password) 
values ('','$name', '$email', '$phn', '$address','$uname', '$password')"; 

if($conn->query($insert)){
 echo 'Data inserted successfully';
}
else{
 echo 'Error '.$conn->error;  
}

mysql_close($connection); // Connection Closed
?>    

The above code submits the form data to the employee table without reloading the page. After submitting the data, it returns 'Data inserted successfully' message and in case of failure, it returns an error message.