How to autosave form as draft in PHP and Ajax without page refresh

Autosaving of form data is a good option for a web form with many input fields. During data entry, the form can be automatically saved as a draft without page refresh. In this topic, I will develop an application to show how you can write PHP code with Ajax and jQuery to implement "Auto Save".

By using Ajax and jQuery form is saved as draft after every few seconds and the user can work on it later to modify/complete the form and submit it.

how to save draft in php and mysqlAssumption

  1. You must have basic knowledge of HTML, CSS, JavaScript/jQuery and PHP.
  2. You must have basic understanding of Ajax. You can read below topics for more details:
    1. How to install xampp for Windows with setup for PHP development
    2. How to write PHP code with examples for beginners
    3. How to build a simple CRUD application in PHP and MySQL

save form data using ajax in phpFolders and Files

Below is a screenshot of the folder structure and files I am using:

Save Form Using Ajax and PHP Without Page Refresh

I have created a folder named 'autosave' under 'xampp/htdocs' as I am using XAMPP. If you are using WAMP, create 'autosave' folder under 'www'.

Folder 'cfg' - In this folder I have kept dbconnect.php which is used to connect to the MySQL database.
Folder 'css' - My custom stylesheet is in this folder
Folder 'js' - In this folder I have my custom JavaScripts file
index.php is my main program that displays a list of applications if available and options to view submitted application and edit draft application.
application_form.php is the application form 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 in database table.
save_application.php - It is the PHP program called from Ajax to save application as draft.

Below is the screenshot of the application form.

save draft in PHP

While entering the values in the form, a JavaScript function will be called every 3 seconds. This function will run an Ajax script which will call a PHP program to save the application in database with status as draft. If you close the form, it will appear in the list of applications with status as draft. User can click on Edit button from the list of applications to further work on it and submit. When application is submitted it's status will change to "Submitted".

Step 1 - Create a MySQL table for user applications

Let us create a table named 'user_application' in MySQL database. This table will have application details, like name, email and age etc. I have a database called 'demo'. So this table will be created in demo database. If you have an existing database other than demo you can also use it. Just make sure same table name does not exist already. Table structure is given below:

draft in ajax in php

Table has 8 columns.

  1. appl_id - It is the primary key and auto incremented id of the application
  2. name - Name of the Applicant
  3. email - Email Id of the Applicant
  4. age - Age of the Applicant
  5. gender - Gender of the Applicant
  6. percent_score - %Score obtained bt the applicant
  7. date - Date of submission or draft submission
  8. status - Status of application (Draft or Submitted)
MySQL create table script for this table is given below, you can use this code to create the table. You can also download code by clicking on download button given later in this topic.

user_application.sql

After you create the table, verify if table structure is same as above. I am not inserting any data in the table initially. By submitting the application or by auto saving the application as draft, data will be inserted in this table.

Step 2 - Connect to MySQL database (dbconnect.php)

Use below script to connect to the database. Note that we have this database connection php program in 'cfg' folder. This is written once and used in every program where database connection is needed. This will be easy for maintenance and also will enable reusability of the code.

dbconnect.php

I am using mysqli_connect() function which needs 4 parameters.

  1. server - in our case it is localhost
  2. userid - we are using root user
  3. password - no password for user root
  4. database name - demo in our case.

If connection is successful, it returns true, false otherwise. We will include this dbconnect.php in other php programs so that we do not need to write it again in the program. For detail database connection understanding please read topic How to Connect to MySQL database in PHP using mysqli_connect.

Step 3 - Display a list of applications (index.php)

In index.php, I will show a list of applications with links to update or view the applications. It is a simple html table where I will select all applications from user_application table and display them along with their status (Draft or Submitted). For each application there will be a link either view (for submitted application) or Edit (for draft application). In addition to this, I will have a button to create a new application.

I have given a sample list of applications below:

Autosave draft using ajax in php

It is a simple html table where I am displaying details of each application in a for loop after fetching from the database. Let's see the code.

index.php

In line 14, I have the button for "New Application" which will open application_form.php for the application form. Then I have defined a html table and within this table I am displaying all applications from database. Just note the line 39. Here, I am checking the status of the application and based on status, I am showing View (Submitted) or Edit (Draft) links to call application_form.php with appl_id as parameter.

Step 4 - Create Application Form (application_form.php)

When user clicks on the "New Application" button or clicks View/Edit links, this program will show the application form where user can enter the data and submit the form. While entering the data, form will automatically be saved after every 3 seconds. If the user closes the form without submitting it, he/she can work on it from list of application later. I will create a simple form with the input fields and two buttons for Submit and Close.

Clicking on Submit button will submit the form and will make the status of application as Submitted. I will use process_application.php to process the application when it is submitted.

Below is the code for application_form.php

application_form.php

Since this program is called with application id as parameter (for submitted or draft application), I checked if application id is available using $_REQUEST['id']. Then I am selecting the application details from the database for the application id. Application status could be either Submitted or Draft or it could be totally a new application. So, if application id is available, I know the status of application. But if it is new application, it's status will be blank. Based on this, I show readonly values in the form if status is submitted, I display the values for edit if status is draft, so that user can update the values.

Step 5 - 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 form data. Script is written in application.js file under js folder.

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 below script:

Here, I am 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 form state has changed and 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 draft. So that is why I will take application id also as input from the form. For new application, application id is blank.

Below are the parameters for Ajax call.

  1. url: save_application.php - this will take the form values and insert/update into user_application table..
  2. method: "POST" - I am using post method.
  3. data: {appl_id:appl_id,name:name, email:email, age:age,gender:gender, score:score} - here I am sending all the form field values.
  4. dataType: "text" - Response from Ajax call will be in text format.

If Ajax is successfully executed, I am checking the value of response, i.e., output of save_application.php. If response is "Error", I display message on the top of the form.

For successful saving of data, appl_id is the response. So, I am writing the appl_id in the form. Note that this appl_id could be a newly generated (for first draft) or it could be the same appl_id which was sent to Ajax call as request parameter to save_application.php (for saving draft more than once).

To display the message for few seconds, setInterval() is used. 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 update user_application table for the $appl_id. If $appli_id is blank, it will insert a row in user_application table. If $appl_id has a value, it will update the user_application table for the appl_id. Below is the code for save_application.php

save_application.php

Now, I will just explain the step when application is submitted. It could be a direct submission or it could a draft application being submitted.

Step 6 - Process Application after Submit (process_application.php)

User can submit the application first time after filling up the application form or user can edit a draft application and submit it.

process_application.php

It takes the values from the form and does some validation. Status of application after successful submission should be "Submitted", but if there is some error, I need to go back to previous status. That is why I added code line 37 to 44. If all validations are successful, I update for existing draft for $appl_id !="" or insert a new application for $appl_id = "". If error occurs or validation fails, I need to go back to previous status, so I added lines 59 and 64 ($status = $prev_status).

Step 7 - Add CSS (style.css)

Let us add below styles. I have already added style.css in index.php and application_form.php.

style.css

These are simple styles. You can always add or change to make the screen look better. Keep this style.css file in your css folder.

save draft feature in formsTest the Application

Make sure in your XAMPP control panel Apache and MySQL services are running. Open the browser and run localhost/autosave. You will see the home page displayed as below:

save as draft in php and ajax

Click on 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 status Draft.

save draft of a form in ajax in php

save form contents as draft in php and ajax

Use edit link to update thr draft application and complete the form then submit. Application should be submitted successfully and status will be "Submitted".

We have now completed the development and testing of the application. Hope you could understand all the steps and you could test it successfully.

save html form as draftImportant Note

  1. In this application I have not used a login option for the user, in a typical application user has to login and submit the application. Here I have not used that so you can submit as many as you want with different email ids.
  2. While saving the draft I 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 draft will be saved. But while submitting you will see validation error messages.
  3. Instead of Auto Save, you can use a button like "Save as Draft", when user clicks on this button form data will be saved. It is the same application I developed using "Save as Draft" button. Only difference will be instead of calling the autoSave function using setInterval(), just call the same function on onClick event of the button. Please refer topic How to develop a save as draft form in PHP and MySQL with Ajax and jQuery.

Scope of Improvement

  1. You can add a login form of the user so that user can login an apply. In that case user can see only his/her application not all applications.
  2. Write code so that draft form can remain for certain number of days. After that the saved form will not be available to edit and submit. You do not want to keep saved form for indefinite period when user never comes back to submit it. So, to reduce unwanted data from database you should keep drafts only for a few days, may be a week or two.

Download source code for Autosave using ajax in PHPDownload Source Code

I have put all codes in a zip file. You can download it by clicking on the Download button below. You do not need to register yourself to download it. You can directly use the code or you can modify them as per your requirements.

add save as draft in form dataConclusion

In this topic I have showed you how you can implement auto saving of the form data using Ajax. I have used only few fields in the form. This was just an example to show how it works. But in actual project you might see a data entry form with many fields in it. In that case Auto Save will be very useful for the users.