CURRENT PROJECTS
loading
CATEGORIES AND POSTS
loading
overset
DEVELOPMENT LOG FOR JIM PALMER
Posted 06/25/2008 in jquery


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:
(function($) {
	// 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);

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:
<?php
	session_start();
	if ( $_REQUEST['saveObject'] )
		$_SESSION['saveObject'] = $_POST['saveObject'];
?>

And the same in Coldfusion:
<!--- ensure clientManagement="Yes" is set in Application.cfc --->
<!--- 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>
comments
loading
new comment
NAME
EMAIL ME ON UPDATES
EMAIL (hidden)
URL
MESSAGE TAGS ALLOWED: <code> <a> <pre class="code [tab4|tabX|inline|bash]"> <br>
PREVIEW COMMENT
TURING TEST
gravatar