Submit a form data without page refresh using PHP, Ajax and Javascript
How can I post a form without refreshing the page?
In this exercise, 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.
Solution:
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 requiring a page refresh.
Database
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 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 employee. This form contains all the fields that the employee table has. In this, we have included the jQuery and Bootstrap libraries.
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.
formscript.js
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 return notification of a successful data submission. It sends the request without reloading the form.
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.
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.
need an explanation for this answer? contact us directly to get an explanation for this answer