We ramble about code, technology and life. Sometimes we actually code...


PHP & JavaScript auto-save

by Kyluke McDougall on 1 July 2015

An auto-save script with PHP and JavaScript.

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 auto-save function for blog posts. It can of course the re-purposed for anything else but this is what it was originally 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 predefined 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 JavaScript script or, if it has been saved elsewhere, update the java script 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