Auto Save a Draft with PHP and jQuery

autosave
Auto save form fields with the help of PHP and jQuery.

Today, I want to go over a simple way of saving your work automatically – by saving a draft of it. Like Gmail, we will save a draft of our work every 2 seconds .

The markup

Here is the structure of the form we will be saving.

The style

Just some simple style for our form.

The javascript

Okay, now for the javascript. Here where we use the setInterval method to save a draft of our work every 2 seconds.

We use jQuery’s $.post function to load data from the server using a HTTP POST request. Our php script is: php/rrpowered-autosave.php.

After we send the request, we will receive content which has been returned in json format from our PHP script. Then after receiving the data from the PHP script, we will add the values to the form. Using the [name='value'] attribute equals selector, we then add the values to the form input fields.

Here is where we send a request to have the form values added to the database.

As mentioned earlier, we will be using the setInterval method to send out form values to the PHP script every 2 seconds. We use the $.post function to load our data from the PHP script and the .serialize() method to get the form values.

Here is th entire javascript code.

The PHP

Now that we have covered the Javascript, let us start with the PHP script.

Start by connecting to the database, then put the posted values from the form into variables.

Check to see if there is a draft already saved for the user.

If there is a draft already saved in the database, then continue to update it.

If the $title variable is set, update the database with the new values from the form – if it is not set, then insert the user’s id and the new posted form values into the database. When the form is first loaded, we load the draft if it exists from the database. Returning it in json format using the json_encode function with an array inside of it.

The entire PHP script.

The database

Thank you for reading and please leave a comment below.

Barrett

Tagged with:

View all contributions by

Website: http://rrpowered.com

Related Articles

Advertisement

Stay connected with us

Add us on Google+

Follow us on Facebook

Follow us on Twitter

Get updates via RSS

Get email updates

FEEDBACK2

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">