Internet, Javascript, Programming
Preserving form data on the fly – Part 1
I recently had the opportunity to interview a celebrity about an upcoming video game that he is involved with. There was a little bit of a challenge to conducting this particular interview because it had to be conducted through Twitter. Twitter isn’t a great avenue for interviews since I didn’t want everyone to see the interview questions and answers before the article was published on my site.
I got to brainstorming and decided I would build a simple form that had the interview questions followed by simple textareas to hold the respective answers. I had to be careful though. I knew if there were any technical glitches there was a chance that this person may just move along and the interview would be over.
A glitch could be anything on my end OR his end. It could range from his browser crashing to there being an issue with the form on submission. An issue that may cause the answers to be lost forever and my chance at conducting this interview would be gone with them.
I got to the drawing board and I came up with a pretty clever solution. As the questions were answered, I would store the answer in a browser cookie while at the same time submit the answer to my server via an AJAX call. This accomplished 2 things
- I could get answers to the interview questions as they were being answered without risk of losing all the form data before the form was submitted or even as the form was submitted.
- I could check for the existence of the answers in the respective cookie when the page was loaded and prepopulate the form fields with the data in the event of a browser crash or some other issue that caused this person to navigate away from the interview questions.
To accomplish all of this and have a form that had a little bit of polish to it, I turned to pForm. pForm is an online form generation tool that lets you pick a color scheme and then use a super easy interface to build your form and then export/download the whole thing when you are done. This was my starting point.
Building the form start to finish took maybe 10 minutes. I can’t remember the last time I spent 10 minutes on a form and got this much done.
With my form in hand, the next step was to get a copy of jQuery and the jQuery Cookie Plugin and start writing some code. If you’ve never used jQuery before, you’ll probably be surprised just how little code we will actually write to get this working. The first step was to go ahead and save the answers to a cookie each time a form field is altered.
To do this we are going to bind an anonymous function to the blur event for all of the textareas on the page. Blur is triggered when the textarea loses focus on the page. We didn’t want to use the change event mostly because it will be called each and every time a new character is added to the textarea. For our purposes, we only want to update when the user indicates that they are done with a particular textarea or input. To do this, we simply add this little bit of code to our header (inside script tags of course):
$(document).ready(function(){ $("textarea").bind("blur", function(e){ $.cookie(this.name, $(this).val(), { path: '/myform', expires: 7 }); }); }); |
What this does is, anytime we change focus from a textarea we are setting a cookie whose name is that of our form field (i.e. a textarea whose name is “text1” will write a cookie named “text1”) and whose data is the value of that form field. Simple enough.
If a user fills in some data for a few of these fields and then refreshes the page, their form fields are empty, but we have preserved the data using cookies so now it’s time to prefill those form elements. The first step is to check those cookies for valid data and autofill any form fields that have cookie data. To do this we are going to expand our document ready jQuery function to include this code:
$("textarea").each( function() { if ($.cookie($(this).attr('name')) != null) { $(this).val($.cookie($(this).attr('name'))); } }); |
What the above code does is iterates through each of the textareas on the page and checks to see if there was data stored in the cookie that matches the textarea and if so, it loads that data into the textarea.
The final piece to this puzzle is to go ahead and initiate a post request immediately after we store the data in the cookie. In this case, I was ok with accepting potentially duplicate submissions for this form because I will be manually reassembling this data as I prepare it to be posted as an article and I can weed out duplicate answers. You’ll need to make that determination based on the purpose of your form and may need to change the behavior.
To initiate the post submission was as easy as adding this to the anonymous function used by the blur event.
$.post("index.php", { div: this.name, answer: $(this).val(), action: "SaveQuestion", question: $("label[for=" + $(this).attr("id") + "]").html() }); |
In the end, the whole code for this should look something like this:
$(document).ready(function(){ $("textarea").bind("blur", function(e){ $.cookie(this.name, $(this).val(), { path: '/myform', expires: 7 }); $.post("index.php", { div: this.name, answer: $(this).val(), action: "SaveQuestion", question: $("label[for=" + $(this).attr("id") + "]").html() }); }); $("textarea").each( function() { if ($.cookie($(this).attr('name')) != null) { $(this).val($.cookie($(this).attr('name'))); } }); }); |
At this point, you are successfully saving data to cookies and you are successfully submitting a request that will save each question on the server side through an AJAX call. In the next part of this article I will show you the server side code that pulls all this together and show you a working demo.
22 Sep 2009 03:55 pm Chris 0 comments