Auto Save with PHP - The Code


10 Jul 15 - 01:14

I promised in a previous blog post that I would be sharing the auto save function.

You can head over to my github page here: auto-save-php to download a copy.

##Function The purpose of these two scripts, are to act as an autosave function for blog posts. It can of course the repurposed for anything else but this is what it was originially intended for.

###How it Works This function works in 2 parts. There is a javascript and a PHP script component. The Javascript calls itself every 5 seconds, gets the values of the pre-defined fields and posts them (via POST) to the PHP script. The PHP script then checks to see if the values posted by the Javascript function already exist in the database or not.

If they do exist, the PHP script will run an update, if they do not exist, PHP will insert those values into the database.

###Javascript Place the javascript into your page. Into either the or the tags. It’s really up to you.

<script src="_js/autosave.js"></script>

Ensure that ‘var url’ is = to the name of your php script which captures the input. In this case, it’s simply ‘autosave.php’

var httpc = new XMLHttpRequest(); // simplified for clarity
var url = "autosave.php"; // PHP script that you'll be passing data to
httpc.open("POST", url, true); // sending as POST

###PHP Save the PHP script ‘autosave.php’ either to the same directory as the javscript script or, if it has been saved elsewhere, update the javascript module to point to the correct folder.

var httpc = new XMLHttpRequest(); // simplified for clarity
var url = "path/to/folder/autosave.php"; // PHP script that you'll be passing data to
httpc.open("POST", url, true); // sending as POST


Archives