I have a large form on my website that I want to be able to autosave to a database as the user is filling it out. Almost identical to how google drive works when typing a document.
I am trying not to have a function that runs every X seconds but rather a function that runs when the user has taken a break in typing. So, if the user has not typed in 1 hour but is still on the page, it doesn't keep pushing save requests.
This is all I have so far which is a basic javascript form submit.
$("#page1Form").submit(function(event){
event.preventDefault();
$changesSaved.text("Saving...");
var url = "/backend/forms/page1-POST.php";
$.ajax({
type: "POST",
url: url,
data: $("#page1Form").serialize(),
success: function(data) { $changesSaved.text(data); }
});
return false;
});
Debounce the textarea change.
Demo: jsFiddle
Put your ajax call in the
saveToDB()
function. These event names('input propertychange change'
) will trigger on any form element change such as radio buttons, inputs, etc.Here is a full demo showing you how to debounce a full form and use ajax to send the data and then return the status (Saving, Saved, etc).
Demo full form and ajax: jsFiddle
Try Sisyphus.js https://github.com/simsalabim/sisyphus. It persists the form data in the browser's local storage and is robust against tabs closing, browser crashes, etc...
I know that this question is old, but I would like to include a code that I like the most. I found it here: http://codetunnel.io/how-to-implement-autosave-in-your-web-app/
Here is the code:
It saves after the user stops writing for more than 750 milliseconds.
It also has a status letting the user know that the changes have been saved or not.