etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

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 time. Using Ajax, we can perform the same procedure without refreshing the web page. 





Ajax is a technique for providing 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 requiring a page refresh.

Submit a form data using PHP, AJAX and Javascript

Database

A database is required to store the form data in the back end. 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 and paste the following command into 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 the employee. This form contains all the fields that the employee table has. In this, we have included the 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 clicking the submit button, the formsubmit() method will be called, which is defined in formscript.js file.



style.css

The style.css file contains the 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 that send the request to the PHP script with the form data and return 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;
}




storeemdata.php

In the above code, ajax calls the storeemdata.php file to store the form data. Generally, we would send data to a server using a 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 sent an asynchronous request to the server to handle the response. We have used the improved version of MySQL. Make sure to replace the database credentials with 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.





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


◀ Previous Article
Divide Large Data Into Two Columns Using PHP
Next Article ▶
Characteristics of a Good Computer Program




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP Create Word Document from HTML
-----------------
How to get data from XML file in PHP
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP code to send email using SMTP
-----------------
Characteristics of a Good Computer Program
-----------------
How to encrypt password in PHP
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
How to add multiple custom markers on google map
-----------------
How to get current directory, filename and code line number in PHP
-----------------
Fibonacci Series Program in PHP
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
How to generate QR Code in PHP
-----------------
Simple pagination in PHP
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
PHP MYSQL Advanced Search Feature
-----------------
PHP Server Side Form Validation
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
jQuery File upload progress bar with file size validation
-----------------
Simple PHP File Cache
-----------------
Simple File Upload Script in PHP
-----------------
Php file based authentication
-----------------
To check whether a year is a leap year or not in php
-----------------
Calculate distance between two locations using PHP
-----------------
PHP User Authentication by IP Address
-----------------
PHP Secure User Registration with Login/logout
-----------------
Simple way to send SMTP mail using Node.js
-----------------
How to print specific part of a web page in javascript
-----------------
Simple Show Hide Menu Navigation
-----------------
Detect Mobile Devices in PHP
-----------------
Polling system using PHP, Ajax and MySql
-----------------
PHP Sending HTML form data to an Email
-----------------
Google Street View API Example
-----------------
Get Visitor\'s location and TimeZone
-----------------
SQL Injection Prevention Techniques
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
Convert MySQL to JSON using PHP
-----------------
Set and Get Cookies in PHP
-----------------
CSS Simple Menu Navigation Bar
-----------------
PHP Programming Error Types
-----------------
Date Timestamp Formats in PHP
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
How to add google map on your website and display address on click marker
-----------------
Write a python program to print all even numbers between 1 to 100
-----------------
How to display PDF file in web page from Database in PHP
-----------------
PHP Getting Document of Remote Address
-----------------
File Upload Validation in PHP
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial






Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2023. All Rights Reserved.