Web storage in action
Now that the basics are covered, it’s time to put HTML5 web storage to use. Assume that, on your website, you have a web form for which you want to provide offline support. It would be great if a user could submit the form and have it sync with the server when the website is back online. This is possible with HTML5.
Create a simple web form that includes a first and last name, email address, and submit button, as shown in Listing 10.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HTML5 Web Storage</title>
<style type="text/css">
label,
input {
display: block;
}
input {
margin-bottom: 10px;
}
</style>
</head>
<body>
<form action="post.php" method="post" id="web-storage-form">
<label for="first-name">First name:</label>
<input type="text" name="first-name" id="first-name">
<label for="last-name">Last name:</label>
<input type="text" name="last-name" id="last-name">
<label for="email-address">Email Address:</label>
<input type="text" name="email-address" id="email-address">
<input type="submit" value="Submit">
</form>
</body>
</html>
The form includes an ID to retrieve the form post and values using JavaScript. It also has CSS to create a basic layout with the form elements. The display:block property on labels and inputs places each element on a new line. The margin-bottom property creates space between the items so the page doesn’t look cluttered.
When a user submits the form, the code first prevents the default post from occurring by retrieving the web-storage-form ID and catching the post using jQuery. When the form posts, you can gather the form values and the URL of the form action to store in variables. You have to serialize the web form values when sending the values as an Asynchronous JavaScript + XML (Ajax) post or storing them in web storage. Before the form is submitted, use the navigator.onLine property to see if the user is currently online.
If the user is online, use the jQuery.post function, which is a shorthand Ajax function, to send and receive the data from the server. This function accepts four arguments: the url to send the data to, the data you are sending (the serialized form values), a callback function that is fired upon a successful request, and a dataType. In this example, the dataType is not included so it uses the default.
If the user is not online, you get fancy with web storage. First, it’s important to see if the browser supports web storage by using the conditional statement you created in Listing 1. If the browser does support web storage, you can save the form values directly to the localStorage object using a custom key. The example uses the formValues custom key. Now that the saving of the localStorage values is in place, check to see if they exist when the user gets back online by adding an if statement to check if localStorage.formValues has a value. If it does, you know that this form was previously submitted to localStorage and can safely send the data to the server using the jQuery.post method that you set up earlier. After the values are submitted, you should remove them from web storage so they’re not accidentally submitted a second time. Listing 11 shows the code in action, from the form post using Ajax to the localStorage.
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
// Check for web storage values from a previous offline session
if(localStorage.formValues) {
console.log("localStorage.formValues: "+ localStorage.formValues);
postForm($("#web-storage-form").attr('action'), localStorage.formValues);
localStorage.removeItem("formValues");
}
$("#web-storage-form").submit(function(event) {
// Prevent the form from posting
event.preventDefault();
// Gather values
var formValues = $(this).serialize();
var url = $(this).attr('action');
postForm(url, formValues);
});
});
function postForm(url, formValues) {
// Post to server or post to web storage
if(navigator.onLine) {
console.log("Online");
$.post(url, formValues, function(data) {
console.log("Success: "+ data);
});
}
else {
console.log("Offline");
if(typeof(Storage) !== "undefined") {
console.log("Storage supported");
localStorage.formValues = formValues;
}
}
}
</script>
To create a complete example, a post.php file acts as the end point of the form post to receive and respond to the form request. This file simply receives the form post and responds by printing the array of key/value pairs, as in Listing 12. When the response is received by the jQuery.post, the data from the response writes to the console.
<?php print_r($_POST); ?>
Of course, you could make the example much more robust. For instance, you could include database storage on the server side and check the localStorage using an interval that constantly monitors whether the user’s computer is back online to submit the form data.
Summary
HTML5 offers a powerful new set of functions that are quickly picking up support from the latest versions of the major web browsers. Web storage is one of the compelling features of HTML5. However, use it wisely. As with cookies, users can turn off web storage. Always have a fallback in place to support those who prefer not to allow this new function.


