Autosave Form Data in PHP and Ajax without Page Refresh
Autosaving of form data is a good option for a web form as users do not need to bother about saving the form as a draft. During data entry, the form can be automatically saved as a draft without page refresh. In this topic, we will develop an application to show how you can write PHP code with Ajax and jQuery to implement "Auto Save". There will be an application form and users can submit the form by filling up all the input fields.
The form can be saved as a draft after every few seconds and the user can work on it later to modify/complete the form and submit it.
Folders and Files
The folder structure and files we will be using:
We have a folder named 'autosave' under 'xampp/htdocs'.
Folder 'cfg' - In this folder we have dbconnect.php to connect to the MySQL database. Folder 'css' - Our custom stylesheet is in this folder Folder 'js' - In this folder we have our custom JavaScripts file index.php is the main program that displays a list of submitted applications with options to view and edit. application_form.php is the application form the user can fill in and submit. process_application.php is the php code written to process the application, that is, it does insert/update application data into the database table. save_application.php - It is the PHP program called from Ajax to save the application as a draft.
Below is the screenshot of the application form.
While entering the values in the form, a JavaScript function will be called every 3 seconds. This function will run an Ajax script that will call a PHP program to save the application in the database with the status as a draft. If you close the form, it will appear in the list of applications with the status as draft. Users can click on the Edit button from the list of applications to further work on it and submit it. When the application is submitted its status will change to "Submitted".
Create a table in MySQL for user applications
We will create a table named 'user_application' in the MySQL database. This table will have application details, like name, email and age, etc. The table structure is given below:
Columns in the table are given below:
appl_id - Primary key and auto-incremented id of the application
name - Name of the Applicant
email - Email Id of the Applicant
age - Age of the Applicant
gender - Gender of the Applicant
percent_score - %Score obtained by the applicant
date - Date of submission or draft submission
status - Application status (Draft or Submitted)
You can download the entire code including create table scripts given later in this topic.
user_application.sql
CREATE TABLE `user_application` (
`appl_id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`age` tinyint(4) NOT NULL,
`gender` enum('Male','Female','Other') NOT NULL,
`percent_score` decimal(5,2) NOT NULL,
`date` date NOT NULL,
`status` enum('Draft','Submitted') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `user_application`
ADD PRIMARY KEY (`appl_id`);
ALTER TABLE `user_application`
MODIFY `appl_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
PHP code to connect to MySQL database (dbconnect.php)
In index.php, we will display a list of applications with options to update and view. It is a simple html table; we will select all applications from the database table and display them along with their status (Draft or Submitted). For each application, there will be a link to view (for submitted application) or edit (for draft application).
A sample list of applications:
We are displaying the details of each application using a for loop after fetching from the database. Let's see the code.
In line 14, there is a button for the "New Application" which calls application_form.php for the new application. Then we have defined an html table displaying all the applications. In line 39, we are checking the application status and showing the View (Submitted) or Edit (Draft) links accordingly.
Create the Application Form (application_form.php)
When the user clicks on the "New Application" button or clicks View/Edit links, this program will show the application form where the user can enter the data and submit the form. While entering the data, the form will automatically be saved after every 3 seconds. If the user closes the form without submitting it, he/she can work on it later.
Clicking on the Submit button will submit the form and will make the application status as Submitted. We will use process_application.php to process the application when it is submitted.
Since this program is called with the application id as a parameter (for submitted or draft applications), we checked if the application id is available using $_REQUEST['id']. Then we select the application details from the database. Application status could be either Submitted or Draft or it can be a new application. So, if the application id is available, we know the application status. But if it is a new application, its status will be blank. Based on this, we show read-only values in the form for submitted status and editable values for draft status.
Write Ajax for Auto Save (application.js)
Auto saving of draft runs every 3 seconds. But it will save data only if there is any change in the form input. jQuery script is written in application.js.
The form state is changed when input data is changed in the form. This form state will be required while running auto-save scripts.
There is a function named autoSave() and this function is called every 3 seconds using setInterval(). See the below code:
setInterval(function(){ // call autosave every 3 seconds
autoSave();
}, 3000);
We are calling autoSave() as a callback function. Now let us see the code for autoSave() function.
Function autoSave()
This function takes the values from the form - name, email, age, gender and score. It will check if the form state has changed, then run Ajax to execute save_application.php. Note that, when a draft is saved, either a new application id is created for the first draft or an existing application id is available when a draft is saved again as a draft. So that is why we will take the application id as input from the form. For a new application, the application id is blank.
function autoSave() {
var appl_id = $('#appl_id').val();
var name = $('#name').val().trim();
var email = $('#email').val().trim();
var age = $('#age').val().trim();
var gender = $('#gender').val().trim();
var score = $('#score').val().trim();
if ($("#frm").data("changed")) { // if data is changed then only save
$.ajax({
url:"save_application.php",
type:"POST",
data:{appl_id:appl_id,name:name,email:email,age:age,gender:gender,score:score},
dataType:"text",
success:function(response)
{
if(response == 'Error')
{
$('#msgSave').html("Error");
}
else {
$('#appl_id').val(response);
$('#msgSave').html("Draft Saved");
}
setInterval(function(){
$('#msgSave').html('');
}, 3000);
$("#frm").data("changed",false); //reset form state
}
});
}
}
Below are the parameters for Ajax request.
url: save_application.php - this will take the form values and insert/update them into user_application table.
type: "POST" - we are using post method.
data: {appl_id:appl_id,name:name, email:email, age:age,gender:gender, score:score} - sending all the form input values.
dataType: "text" - Response from Ajax call will be in text format.
If Ajax is successfully executed, we check the value of the response, i.e., the output of save_application.php. If the response is "Error", we display a message on the top of the form.
For successful saving of data, appl_id is the response. So, we are writing the appl_id in the form. Note that this appl_id could be newly generated (for the first draft) or it could be the same appl_id that was sent to Ajax call as a request parameter to save_application.php (for saving draft more than once).
To display the message for a few seconds, setInterval() is used. The form state is changed to false, as data is saved now.
Now, let's see the code of save_application.php. It simply takes the input values and inserts a new row in user_application table or updates user_application table for the $appl_id. If $appli_id is blank, it will insert a row and if $appl_id has a value, it will update the existing row. Below is the code for save_application.php
Now, we will explain the steps when the application is submitted. It could be a direct submission or a draft application being submitted.
Process Application after Submit ( process_application.php)
The user can submit the application the first time after filling up the application form or edit a draft application and submit it.
process_application.php
<?php
if (isset($_POST['submit'])){
$appl_id = $_POST['appl_id'];
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$name = mysqli_real_escape_string($conn,$name);
$age = $_POST['age'];
$gender = $_POST['gender'];
$score = $_POST['score'];
$curr_dt = date('Y-m-d');
// do some validation
if (!filter_var($email,FILTER_VALIDATE_EMAIL)){
$email_err = "Invalid Email format";
$err_flg = true;
}
else { // check if email id already exists
if($appl_id !="") // existing draft application, same email id should not exists for other application
$sql = "select * from user_application where email ='$email' and appl_id <> $appl_id";
else
$sql = "select * from user_application where email ='$email'";
$rs = mysqli_query($conn,$sql);
if (mysqli_num_rows($rs) > 0) {
$email_err = "Email Id already exists";
$err_flg = true;
}
}
if($age <18 || $age >35){
$age_err = "Age must be between 18 and 35";
$err_flg = true;
}
if($score < 35 || $score > 100){
$score_err = "Score percentage must be between 35 and 100";
$err_flg = true;
}
if($appl_id != "") { // draft
$prev_status = "Draft";
$status = "Submitted";
}
else {
$prev_status = "";
$status = "Submitted";
}
if (!$err_flg) {
if($appl_id !="") { // update draft
$update="update user_application set name='$name', email='$email', age='$age', gender='$gender', percent_score = '$score', date = '$curr_dt', status = '$status' where appl_id = '$appl_id'";
$result=mysqli_query($conn,$update);
}
else { // insert
$insert="insert into user_application (name, email, age, gender, percent_score, date, status) values ('$name','$email','$age','$gender','$score','$curr_dt','$status')";
$result=mysqli_query($conn,$insert);
$appl_id = mysqli_insert_id($conn); // newly generated appl_id
}
if ($result)
echo "<h4 style='text-align:center;color:green'>Your Application submitted successfully.";
else {
$status = $prev_status;
echo "<h4 style='text-align:center;color:red;'>Could not submit your Application, Error occurred.<a href='index.php'> Application List</a></h4>";
}
}
else
$status = $prev_status;
}
It takes the values from the form and does some basic validations. The application status after successful submission should be "Submitted", but if there is some error, we need to go back to the previous status. That is why we added the code in lines 37 to 44. If all validations are successful, we update the existing draft or insert a new application. If an error occurs or validation fails, we need to go back to the previous status, so we added lines 59 and 64 ($status = $prev_status).
Add CSS (style.css)
Let us add the below styles. We have already added style.css in index.php and application_form.php.
Verify that Apache and MySQL services are running in the XAMPP control panel. Run localhost/autosave in the browser. You will see the home page.
Click on the New Application button and enter values, you will see while you are entering the values, a message appearing on top of the form saying "Draft Saved". Close the application. You will see your application is saved with the status Draft.
Use the edit link to update the draft application and submit it. Application should be submitted successfully and status will be "Submitted".
We have now completed the development and testing of the application.
Important Note
While saving the draft we have not used validation for email id, age and marks. But, during submission, these are being validated. So, you can enter anything in these fields and the draft will be saved. But while submitting you will see validation error messages.
Instead of Auto Save, you can use a button like "Save as Draft", when the user clicks on this button form data will be saved. The only difference will be instead of calling the autoSave function using setInterval(), just call the same function on the onClick event of the button.
Download Source Code
Download the source code by clicking the download button below:
Conclusion
In this topic, we have seen how you can implement auto-saving of the form using Ajax. We have used only a few fields in the form. This was just an example to show how it works. However, in the project, you may see a data entry form with many fields. In that case, Auto Save will be useful for the users.
Post a Comment