Submit a form data without page refresh using PHP, Ajax and Javascript

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 times. 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 ability to perform tasks on web page without page refresh.

Submit a form data using PHP, AJAX and Javascript

Database

To store the form data in 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`)
)




employee_form.php

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.

php_ajax_form


<!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.



style.css

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; }




formscript.js

The formscript.js file contains validation code and the else part of this code contains ajax codes which sends the request to the PHP script with the form data and returns notification of 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;
}




storeemdata.php

In the above code, ajax code calls the storeemdata.php file to store the form data. Generally, we would send data to server using POST request, the server handles it and send 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 error message.




Related Articles

Preventing Cross Site Request Forgeries(CSRF) in PHP
PHP code to send email using SMTP
Simple pagination in PHP
Simple PHP File Cache
PHP Connection and File Handling on FTP Server
CRUD operations in Python using MYSQL Connector
Windows commands to Create and Run first Django app
How to send emojis in email subject and body using PHP
PHP7.3 New Features, Functions and Deprecated Functions
Create pie chart using google api
How to display PDF file in PHP from database
How to read CSV file in PHP and store in MySQL
Create And Download Word Document in PHP
PHP SplFileObject Standard Library
Simple File Upload Script in PHP
Sending form data to an email using PHP






Read more articles


General Knowledge



Learn Popular Language