
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<html lang="en"> <head> <meta charset="UTF-8" /> <title>Auto Save Draft | RRPowered</title> <link rel="stylesheet" type="text/css" href="css/rrpowered-autosavedraft.css" /> <script rel="text/javascript" src="javascript/jquery.js"></script> <script rel="text/javascript" src="javascript/rrpowered-autosavedraft.js"></script> </head> <body> <div class="center"> <div class="saved"></div> <form> <input type="text" name="title" placeholder="Title" autofocus> <textarea type="text" name="body" placeholder="Body"></textarea> <input type="submit" value="Send"> </form> </div> </body> </html> |
The style
Just some simple style for our form.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
body, textarea { font-family: "arial"; } .center { width: 780px; margin: 100px auto; } input[type="text"], textarea { padding: 20px; margin: 5px; -moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px; border: solid #c5c5c5 1px; font-size: 20px; outline: none; width: 40.5em; } input[type="text"]:hover, textarea:hover { border: solid #666 1px; } textarea { height: 300px; } input[type="submit"] { margin: 5px; background: #2ca5f5; background-image: -webkit-linear-gradient(top, #2ca5f5, #2f90cc); background-image: -moz-linear-gradient(top, #2ca5f5, #2f90cc); background-image: -ms-linear-gradient(top, #2ca5f5, #2f90cc); background-image: -o-linear-gradient(top, #2ca5f5, #2f90cc); background-image: linear-gradient(to bottom, #2ca5f5, #2f90cc); -webkit-border-radius: 4; -moz-border-radius: 4; border-radius: 4px; font-family: Arial; color: #ffffff; font-size: 20px; padding: 20px 30px; text-decoration: none; border: none; cursor: pointer; } input[type="submit"]:hover { background: #3cb0fd; background-image: -webkit-linear-gradient(top, #3cb0fd, #3498db); background-image: -moz-linear-gradient(top, #3cb0fd, #3498db); background-image: -ms-linear-gradient(top, #3cb0fd, #3498db); background-image: -o-linear-gradient(top, #3cb0fd, #3498db); background-image: linear-gradient(to bottom, #3cb0fd, #3498db); text-decoration: none; } ::-webkit-input-placeholder {/* WebKit browsers */ color: #c5c5c5; } :-moz-placeholder {/* Mozilla Firefox 4 to 18 */ color: #c5c5c5; opacity: 1; } ::-moz-placeholder {/* Mozilla Firefox 19+ */ color: #c5c5c5; opacity: 1; } :-ms-input-placeholder {/* Internet Explorer 10+ */ color: #c5c5c5; } input[type=text]:focus, textarea:focus { box-shadow: 0 0 5px rgba(46, 100, 254, 1); border: 1px solid rgba(46, 100, 254, 1); padding: 20px; margin: 5px; font-size: 20px; } |
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.
1 2 3 |
$.post("php/rrpowered-autosave.php", function (data) { .... }, "json"); |
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.
1 2 3 4 |
$.post("php/rrpowered-autosave.php", function (data) { $("[name='title']").val(data.title); $("[name='body']").val(data.body); }, "json"); |
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.
1 2 3 |
setInterval(function () { $.post("php/rrpowered-autosave.php", $("form").serialize()); }, 2000); |
Here is th entire javascript code.
1 2 3 4 5 6 7 8 9 |
$(function () { $.post("php/rrpowered-autosave.php", function (data) { $("[name='title']").val(data.title); $("[name='body']").val(data.body); }, "json"); setInterval(function () { $.post("php/rrpowered-autosave.php", $("form").serialize()); }, 2000); }); |
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.
1 2 3 4 5 6 7 8 9 10 |
try { /*Connect to the database*/ $dc = new PDO("mysql:host=localhost;dbname=test", 'root', '*******'); /*Get the posted values from the form*/ $title=&$_POST['title']; $body=&$_POST['body']; $gtmsg=&$_POST['gtmsg']; /*Get user id*/ $user_id=1; |
Check to see if there is a draft already saved for the user.
1 2 |
$stmt = $dc->query("SELECT * FROM autosave WHERE user='$user_id'"); $return_count = $stmt->rowCount(); |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
if($return_count > 0){ if(isset($title)){ /*Update autosave*/ $update_qry = $dc->prepare("UPDATE autosave SET msg_title='$title', msg_body='$body' WHERE user='$user_id'"); $update_qry -> execute(); } else { /*Get saved data from database*/ $get_autosave = $dc->prepare("SELECT * FROM autosave WHERE user='$user_id'"); $get_autosave->execute(); while ($gt_v = $get_autosave->fetch(PDO::FETCH_ASSOC)) { $title=$gt_v['msg_title']; $body=$gt_v['msg_body']; echo json_encode(array('title' => $title, 'body' => $body)); } } } else { /*Insert the variables into the database*/ $insert_qry = $dc->prepare("INSERT INTO autosave (user, msg_title, msg_body) VALUES (?, ?, ?)"); $insert_qry->execute(array($user_id, $title, $body)); } |
The entire PHP script.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<?php try { /*Connect to the database*/ $dc = new PDO("mysql:host=localhost;dbname=test", 'root', '*******'); /*Get the posted values from the form*/ $title=&$_POST['title']; $body=&$_POST['body']; $gtmsg=&$_POST['gtmsg']; /*Get user id*/ $user_id=1; $stmt = $dc->query("SELECT * FROM autosave WHERE user='$user_id'"); $return_count = $stmt->rowCount(); if($return_count > 0){ if(isset($title)){ /*Update autosave*/ $update_qry = $dc->prepare("UPDATE autosave SET msg_title='$title', msg_body='$body' WHERE user='$user_id'"); $update_qry -> execute(); } else { /*Get saved data from database*/ $get_autosave = $dc->prepare("SELECT * FROM autosave WHERE user='$user_id'"); $get_autosave->execute(); while ($gt_v = $get_autosave->fetch(PDO::FETCH_ASSOC)) { $title=$gt_v['msg_title']; $body=$gt_v['msg_body']; echo json_encode(array('title' => $title, 'body' => $body)); } } } else { /*Insert the variables into the database*/ $insert_qry = $dc->prepare("INSERT INTO autosave (user, msg_title, msg_body) VALUES (?, ?, ?)"); $insert_qry->execute(array($user_id, $title, $body)); } } catch(PDOException $e) { echo $e->getMessage(); } ?> |
The database
1 2 3 4 5 6 7 |
CREATE TABLE IF NOT EXISTS `autosave` ( `id` int(15) NOT NULL AUTO_INCREMENT, `user` varchar(255) NOT NULL, `msg_title` varchar(255) NOT NULL, `msg_body` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ; |
Thank you for reading and please leave a comment below.

This is great! Thanks!
Hi Barrett !
great job man, i like your topics so much
keep it up ..