
| home | AJAX (8) || C#.NET (7) || Coldfusion Development (16) || DHTML (15) || Flash Development (19) || jQuery (8) || MSSQL (2) || UNIX (10) |
| 6.25.08 | Simple jQuery Auto Save |
GOAL
To provied a simple and automated means of automatically saving a specific global Javascript object shortly after the value of said object changes. This must support complex and multidimensional objects and save the complete changed object to a session handling backend via AJAX.
The solution I quickly put together involves a quick jQuery script with an example PHP and Coldfusion handler which does the server-side storage of the object to be saved as a native JSON (JavaScript Object Notation) string in the native server session storage mechanism. In the real world I’d change this to store in the database and would use a different language, but this is merely here for a proof of concept on how simple this task is.
Here’s the jQuery plugin-ish script you only need that will only need included and the interval will start saving upon the document.onLoad even being thrown and it’s spot in the $(document).ready queue being processed:
// configure this to the globally available object you would like to autosave
$.autoSave.object = _cart;
// load checking function on interval to autosave via AJAX
$(document).ready( function () {
// the jquery.json.js plugin must be included
if ( typeof($.toJSON) != 'function' ) return false;
// setup the interval function - ensure only once.
$.autoSave.intervalId = $.autoSave.intervalId || window.setInterval(function () {
// only if the object has changed value in any way - this is a semi-expensive operation
if ( $.toJSON($.autoSave.object) != $.autoSave._oldObjString )
// formulate a simple POST with the JSON serialized data to save in the session
$.ajax({data: 'saveObject=' + $.toJSON($.autoSave.object),
type: 'POST',
success: function () { $.autoSave._oldObjString = $.toJSON($.autoSave.object); },
url: 'saveHandler.php'});
}, 900);
} );
})(jQuery);
Download this code: jquery-autosave/jquery.autosave.js
Here’s an example PHP script to handle the incoming JSON string to be stored in the default session mechanism in all its glorious PHP simplicity:
// write the new object to the session variable
if ( $_REQUEST['saveObject'] )
$_SESSION['saveObject'] = $_POST['saveObject'];
?>
Download this code: jquery-autosave/saveHandler.php
And the same in Coldfusion:
<!--- if new object, save in the CLIENT variables (albeit limited in length) --->
<cfif IsDefind('FORM.saveObject') and Len(FORM.saveObject) gt 0>
<cfset CLIENT.saveObject = FORM.saveObject>
</cfif>
Download this code: jquery-autosave/saveHandler.cfm
No comments