Reputation: 37
I need a script that will store html form data locally on the device until the user is online and then submit the form via the html action. Is this possible? I'm a javascript novice so I'd love any help available.
Upvotes: 0
Views: 868
Reputation: 646
I think this is doable. Here's how I would do it, though it may not be ideal.
Set your form up so that the submit action is handled by javascript. It should attempt to submit the form with something like an XMLHttpRequest
or jQuery's ajax()
function.
Set up callbacks for the submission request. On success, indicate this to the user or navigate to some new page, however you want to show the request was successful. On failure (any failure or use the result's status code to confirm that the user is unable to connect) you have two options.
One option is to do a setTimeout
of some reasonable length and attempt your submit action again. If the user closes the page or navigates away, though, this will never complete.
Another option is to put the form data into an array of some sort and put it into the localStorage
object. Then if they reload the page, you can see if that data exists. If it does, it can repopulate the form and prompt the user to attempt a new submission. If the submission is successful, empty the local storage.
The way I'd do it would be a combination of both. Here's some psuedocode.
//run this once document is ready
//our submitForm action
var submitForm = function() {
var url = "my_form_action.php";
var params = "foo=bar"; //set params to your form values here
localStorage.myFormData = params;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
//Call a function when the state changes.
http.onreadystatechange = function() {
if(http.readyState == 4) {
if(http.status == 200) {
//call was completed successfully
//clear out our local storage
localStorage.myFormData = null;
//do whatever here! (tell the user it was successful, change pages, whatever)
//doStuff();
} else {
//call was unsuccessful (user is offline)
//attempt again in 10 seconds
window.setTimeout(submitForm, 10000);
}
}
}
http.send(params)
}
//on document ready, check if we have pending form data to send
//if we do, fill in our form and attempt to submit it
if(localStorage.myFormData) {
//my data exists
//fill the form back out using stuff like
//document.getElementById('FirstName').value = localStorage.myFormData.match(/(.+?)=(.+?)(?:&|$)/g)[1][1];
//you'll need to figure out how best to repopulate your form when the page loads, but do it here
//once form is repopulated, either submit it using the form.submit function or call our submitForm() function directly
submitForm();
}
I hope this makes sense. There's a lot of work involved in getting the above setup working, but it should work!
Upvotes: 2