Wednesday, March 14, 2007

autoSave - jQuery plugin

autoSave is the result of one too many user complaints about losing data due to session timeouts, power outages, meteor strikes and other issues beyond my control. You can feed it one or all of your form fields and it will do an ajax post to your server whenever any of those values change, with a delay built in for text-type fields to minimize the number of ajax calls your application makes.

Overkill? Possibly, but this was more of an experiment than anything and since it could prove useful in rare circumstances I'm making it available.

Please be kind - I have no formal programming training of any kind, so the code might be somewhat lacking in elegance. In fact, "somewhat" might be a bit of an understatement...

Usage: $("yourFormInputs").autoSave( Function, Map );

Function: Any ajax function. The function is called in the scope of the element itself so "this" refers to the element's properties: this.id, this.value, this.checked, etc.

Map: Key/value pairs as parameters
  • delay(ms) - for text fields, how long to wait before posting. default 1000ms
  • beforeClass - class to apply to the element when the value has changed
  • afterClass - class to apply to the element after the ajax call has returned
  • onChange - function to run when the value changes. By default applies beforeClass
  • preSave - function to run just before the ajax function is run. Returning a boolean"false" from this function will prevent the ajax call from running and reverts the field to its previous value. All other return values allow the ajax callto run normally. ( Of limited use, but why not... )
    • One possible use: { preSave : function (){ return confirm('are you sure?'); } }
  • postSave - function to run when the ajax call completes. By default applies afterClass

Caveats: Checkboxes have to be handled specially since they don't have separate values for checked and unchecked states. See below for one possible solution.

Example: ( I need to find a script formatter...)

$(document).ready(function(){

$(":input").autoSave(function(){

var ele = new Object();

// remember that this function runs in the scope of the element itself.
ele[this.name] = (this.type =="checkbox") ? this.value + "|" + this.checked : this.value;

$.post("test.cfm", ele, function (data) {$("#ResultDiv").empty().append(data);} )

});
});


You can download it here: jQuery.autoSave.js

2 comments:

Tony said...

The host to your js seems to have taken it down.

And a link to SO question for ajax autosave: http://stackoverflow.com/questions/931252/ajax-autosave

Unknown said...

Hi i tried using your code on a full form, i used the id, as the id of form. And used method post and url in AJAX. But it doesn't seem working. I know that your answer on stack is really popular for it. But please help me out with it.