Saving form input when you are offline using localStorage

28 February 2011

Leading on from the work I did with the application cache, I became interested in using local storage to allow me to input data into a form and save it offline, ready for synching later on when I was online.

I've made use of JSON.js for handling JSON and jQuery in the code below for some convenience, you should be able to swap out for your library of choice.

Some caveats: Inspiration:

OnOffApp makes use of local storage to save form input locally when a user is offline and allow them to synchronise it when they are back online again.
Dependencies:	json.js
Config:			when calling init, there are 5 items that can be optionally configured
					unique identifier for the form to be used in local storage as the key
					jQuery object of the field that supplies the id, used to find the parent form, otherwise form defaults to all forms on page
					HTML to display to inform the user they have items to be synchronised to the server
					HTML for synchronising button
					HTML for the message to show the user when local storage is full and data cannot be saved

OnOffApp = (function(){
	//variables available throughout the function
	var UID;
	var postForm = $("form");
	var holder = $("<div id=\"synchMsg\"></div>");
	var config = {};
	//initialiser function
	//@argument usrconfig: an object of config options
	var init = function(usrconfig){
		var submit_button = postForm.delegate("input[type=submit]", "click", submit_click);
		if(retrieveLocalData() === true){
		$(window).bind("online", synchMessage);
		$(window).bind("offline", synchMessage_remove);
	//set-up defaults for user configurable messages and overwrite where specified
	//@arguments usrconfig: object of user-set options
	//@returns the config object
	var setup_config = function(usrconfig){
		var id = location.href;
		config.synchMsg = "<p class=\"synch\">Locally saved data can be synchronised now</p>";
		config.synchBtn = "<input type=\"submit\" value=\"Synch\" class=\"synch\" />";
		config.warnMsg = "<p class=\"warn\">Local storage is full.</p>";
		 for(var i in usrconfig){
			if(i === "id"){
				id = usrconfig[i].val();
			else if(i === "field_id"){
				postForm = usrconfig[i].closest("form");
			config[i] = usrconfig[i];
		 UID = "uID-" + id;
		 return config;
	//submit button clicked
	//detect if we are online.  If so, grab any saved data as well as existing data and save via AJAX, if not save to local storage
	var submit_click = function(e){
		var data = getFormInput();
		var savedData = $.parseJSON(getLocalData());
	//get the form inputs and put into object notation
	//@returns an object
	var getFormInput = function(){
		var formArray = postForm.serializeArray(),
			o = {};
			$.each(formArray, function(){
				o[] = this.value;
		return o;
	//get localStorage data
	//@returns string of locally stored data or an empty string
	var getLocalData = function(){
		return localStorage.getItem(UID) || "";
	//set localStorage data, if out of space add a warning instead
	var setLocalData = function(data){
		try {
			localStorage.setItem(UID, data);
		catch (e) {
			if (e == QUOTA_EXCEEDED_ERR) {
	//get the data from localStorage and add saved values into the relevant fields
	//@returns true or false depending on whether there was locally stored data
	var retrieveLocalData = function(){
		var oldData = getLocalData();
		if(oldData !== ""){
			var fields = $.parseJSON(oldData),
			$.each(fields, function(key, val){
				field = $("[name=" + key + "]");
				if(field.length > 0){
					if(":checkbox") ||":radio")){
						field.attr("checked", "checked");
			return true;
		return false;
	//if you have localStorage data and you are online, prompt the user to synchronise their data (i.e. save it to the server)
	var synchMessage = function(){
		if(navigator.onLine && getLocalData() !== ""){
			if($("#synchMsg").length === 0){
	//remove the synch message
	var synchMessage_remove = function(){
	//save form data to the server via AJAX
	var saveToServer = function(data){
		var url = postForm.attr("action");
		var params = $.param(data);
		var me = this;
			method: "post",
			url: url,
			data: params,
			success: savedSuccess(data)
	//after data saved to server, remove the saved data from localStorage and remove the synchronise message
	var savedSuccess = function(){
	//interfacing methods and properties
	return {
		init: init

//For the purposes of the demo, there is a hidden input with id "post_id" with the unique identifier for the post (like Wordpress)
	try {
		if('localStorage' in window && window['localStorage'] !== null){
				"id_field" : $("#post_id"),
				"id" : $("#post_id").val(),
				"warnMsg" : "<p class=\"warn\">Sorry, your local storage is full up.  Please copy and save your latest work to a text file and go online to synchronise your work as soon as you can.</p>",
				"synchMsg" : "<p class=\"synch\">You have locally saved data that you can now synchronise with the live server</p>"
	catch(e) {
		return false;