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=newPDO("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.