Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
189
rated 0 times [  191] [ 2]  / answers: 1 / hits: 32598  / 11 Years ago, mon, november 11, 2013, 12:00:00

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;
});

More From » jquery

 Answers
341

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.



var timeoutId;
$('#the-textarea').on('input propertychange change', function() {
console.log('Textarea Change');

clearTimeout(timeoutId);
timeoutId = setTimeout(function() {
// Runs 1 second (1000 ms) after the last change
saveToDB();
}, 1000);
});

function saveToDB()
{
console.log('Saving to the db');
}





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


[#74352] Sunday, November 10, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leog

Total Points: 225
Total Questions: 113
Total Answers: 118

Location: Oman
Member since Wed, Apr 12, 2023
1 Year ago
;