Auto-saving with jQuery

Posted by Jetlogs @ 2:22 am
Category: jQuery,PHP,Web Development

Auto-saving has been one of the great features that AJAX has given to us. Ever had a time when you were writing a very long article and suddenly, your browser crashes. Thanks to applications that implement auto-saving, data is less prone from lost due to these cases.

Ever wondered how auto-saving is done? Basically, it is just a simple AJAX script running in the background at set intervals to save the data you are currently working on. Here is a simple tutorial on how to implement auto-saving using jQuery

Before we start, the article assumed the following:

  • Basic knowledge of jQuery
  • Basic knowledge of PHP

For the articles database, we will only use 4 rows for our table named articles:

  • id – this will serve as the primary index for the table; auto-increment
  • title – this will contain the title of the article
  • content – this will contain the body of the article itself
  • timestamp – this will contain the timestamp when the row was last inserted or updated

Let us first start with the form and call it add_article.php for this tutorial. Before we render our form, we must first create a blank instance of a row. The purpose of this is two-fold. One, so that we can generate an article id, and secondly that we cannot really update a non-existent row. There is a more efficient way of implementing this logic without generating a blank row every time, however, for the sake of simplicity and explaining the point of concept for this tutorial, we will skip this part.

add_article.php

//create new article on database
mysql_query("INSERT INTO `articles`(title, content) VALUES('', '')");
$article_id = mysql_insert_id();

The next step is making the form. First, we would create a form element that would to save the article to a standard save page. Lets call it save.php.

Remember the article_id generated in making the blank row? Now we must output it as a hidden input for the article_id associated with the article. We would also need an input text field for the title and a text area for the content. Finally we would need a submit button, and a placeholder container for the “Last saved” timestamp.

add_article.php

<form id="article_form" method="post" action="save.php">

Title:<br />
<input type="text" name="title" id="txt_title" /><br />
Content:<br />
<textarea name="content" id="txt_content" ></textarea><br />
<input type="hidden" name="article_id"
value="<?php echo $article_id ?>" />

<input type="submit" value="Save"/><br />

</form>
<div id="timestamp"></div>

Now for our AJAX back end, we must create a script that will perform the update from the AJAX request that came from add_article.php. Let us call this script autosave.php. In return, the script must output the timestamp when the article was last updated

autosave.php

$title = mysql_real_escape_string($_POST['title']);
$content = mysql_real_escape_string($_POST['content']);
$id = (int)$_POST['article_id'];

//save contents to database
mysql_query("UPDATE `articles`
    SET title = '$title', content = '$content' WHERE id = '$id'");

//get timestamp
$result = mysql_query("SELECT timestamp FROM `articles`
    WHERE id = $id");
$timestamp = mysql_result($result, 0);

//output timestamp
echo 'Last Saved: ', $timestamp;

And finally to tie it all up, we must now create the autosave script in jQuery on add_article.php. First of all, in creating our autosave() function, we will need to create a setTimeout loop that will call itself recursively. For this tutorial, the interval between auto-saving is 20 seconds

add_article.php

function autosave()
{
	var t = setTimeout("autosave()", 20000);
}

And finally, to finish it all up, we must send an AJAX request to our back end autosave.php. Of course, we mustn’t forget to pass the $article_id we generated earlier. Also, auto-saving must only proceed when both title and contents are not empty.

And lastly, when the AJAX request has been successfully processed, we will pass its value to our timestamp container.

add_article.php

function autosave()
{
	var t = setTimeout("autosave()", 20000);

	var title = $("#txt_title").val();
	var content = $("#txt_content").val();

	if (title.length > 0 || content.length > 0)
	{
		$.ajax(
		{
			type: "POST",
			url: "autosave.php",
			data: "article_id=" + <?php echo $article_id ?>
+ "&title=" + title + "&content=" + content,
			cache: false,
			success: function(message)
			{
				$("#timestamp").empty().append(message);
			}
		});
	}
}

Finally, it is just a matter of starting the auto-saving feature when the DOM is ready:

add_article.php

$(document).ready(function(){
	autosave();
});

Working demo of the tutorial and the download links can be found below:

View jQuery Auto-save Demo
Download Source Codes


22 Comments »

22 Comments to “Auto-saving with jQuery”

  1. farreina
    1

    is it possible to auto save in PHP without any action? for example, I would like to save data at certain time and day without user have to refresh the page or without user have to log-in into the page.

  2. Jetlogs
    2
    Author Comment

    Is this like doing automatic daily/weekly backups? For that you will need to do a CRON job.

    Make a script that will perform the save action, and then configure the server to run the script at the certain time or day of the week through the CRON tab on your host.

    So no user interaction will be needed to automatically save/backup.

  3. Mark
    3

    Hello,

    This is a very good, helpful tutorial.

    At the beginning of the tutorial, you mentioned there is more efficient logic than to add a blank row each time. I am wondering if you have implemented such a logic and have the more-complex code available?

    Thank you for your time and tutorials,

    Mark

  4. Job
    4

    Hello, your script is very good, but I can’t autosave when the form have 5 fields…

  5. EmmaLou
    5

    Hey, I have implemented this on a site, and it’s working wonderfully. It’s a rather large form that the users were having problems with time outs while updating. This has solved that issue.
    The only hiccup that I am seeing, and I’m not sure why is that if a person puts an ‘&’ sign in the text box during the autosave, it removes ALL the text after the & sign. Can you replicate this? or do you have any solutions?

    I’ve set up a function to replace the ‘&’ sign, however, I’m not sure it’s replacing it before it gets to the autosave feature.

    Curious to know your thoughts.

  6. Jetlogs
    6
    Author Comment

    Try the Javascript escape function:

    data: “article_id=” + < ?php echo $article_id ?>
    + “&title=” + escape(title) + “&content=” + escape(content),

  7. J-F Lacrampe
    7

    “There is a more efficient way of implementing this logic without generating a blank row every time, however, for the sake of simplicity and explaining the point of concept for this tutorial, we will skip this part.”

    It would be of great help to me to explain the logic behind this – I don’t need the code itself, just an information on how you would do that. Creating a blank row every time is a hassle for me and my users.

    Thanks.

  8. Jetlogs
    8
    Author Comment

    @J-F Lacrampe:

    The approach for that one would be to check first whether the user input is not empty before creating a row in the database. However, the article_id will instead be stored in the session:

    autosave.php

    
    if ((!empty($title) || !empty($content))
    {
       if (empty($_SESSION['article_id'])
       {
          //create new article on database
          mysql_query("INSERT INTO `articles`(title, content)
          VALUES($title, $content)");
          $_SESSION['article_id'] = mysql_insert_id();
       }
       else
       {
           mysql_query("UPDATE `articles`
           SET title = '$title', content = '$content'
           WHERE id = '".(int)$_SESSION['article_id']."'");
       }
    }

    of course for every instance of add_article.php you need to destroy any leftover sessions from previous instances:

    add_article.php

    
    unset($_SESSION['article_id']);
    
  9. Vikas Tharyani
    9

    I have a table which have the following fields
    deck_date
    deck_id
    user_id
    deck_name
    school
    course
    professor
    type_deck
    subtype_deck
    special_note
    status
    timestamp

    when i try to autosave using the above Jquery, autosave.php, and add_articel.php, the problem i am facing is that i get only the timestamp value correct rest nothing is stored in the table named deck
    in place of add_article.php i have a file named createflashacrd.php in which i have following text fields
    school
    course
    professor
    type_deck
    subtype_deck
    special_note
    status

  10. Natan
    10

    Thanks,

    Very simple and easy to implement!

  11. Nick Coupland
    11

    Hi just wondering if you know of a way to integrate this with tinyMCE. For some reason when i enable the tinyMCE script the autosave no longer pushes the content in the textarea to the database. Every other input field is fine, its only the tinyMCE one that is affected.
    Thanks
    Nick

  12. Russ
    12

    I’m new to AJAX and wanted an autosave script for a CMS I am developing. This worked out fine for me. I also included a loading image when the ajax call is processed. Took me a minute to figure that out.

    It was a lot easier than I thought it was going to be. I simply rewrote the html of the #timestamp with an image and text just before the call.


    $(“#timestamp”).html(” Saving page data…”);

    $.ajax({

    Thanks for the great script!

  13. Russ
    13

    whoops, the IMG tag disappeared. it was just a basic image tag with basic attributes. nothing special.

  14. Russ
    14

    One other comment in case anyone is trying to find out an answer. I ran into a problem with posting PHP content through this form with loops and incremented variables. The plus sings (+) weren’t being encoded. The escape() function does not encode the following characters {* @ – _ + . /}. Thus it was crashing my scripts that were in the form field. Although it’s not entirely fail-safe, the function encodeURIComponent() worked out just fine for me.

    So instead of using:
    “&title=” + escape(title)

    Use:
    “&title=” + encodeURIComponent(title)

  15. Donna
    15

    I wonder jQuery has an important role in making the article of the sites. Melbourne Functions

  16. Bulsionvili
    16

    Руководитель

  17. Ravi Kumar
    17

    Hi,

    First of all I want to say thanks to you, because this article helped me a lot. Keep posting like these

    Thanks

  18. Malith
    18

    Thank you.. This was very helpful..!!

  19. Bunthan
    19

    Thanks very helpful for me……….

  20. Pingback:
    20
    What's intaglioing or nonhistorical

    [...] [...]

  21. joe
    21

    This is very helpful, it takes only 10 mins to implement! wonderful post! :D

  22. Pingback:
    22
    Oldskool Linkdump from 2009 | Reverse The Web

    [...] weblog – AJAX : A Basic Example and a BookmarkletAgile Ajax: Ajax ApplicationsJetlogs.org » Auto-saving with jQueryPeopleSoft Auto-Save with Ajax – ITtoolboxWikiMD5 in JavascriptPaj’s Home: Cryptography: [...]

RSS Comment Feed Comments RSS |trackback TrackBack URI

Leave a comment

  • Archives

  • Donations

  • Social Bookmarks

  • Jetlogs.org
    Some Rights Reserved 2007
    Creative Commons License