Save 1 second after Form Change (includes ajax call)

Debouncing form input change

by Eric

HTML

Modify the form all you want. It will only save 1 second after you are done making changes to whatever input.
<br />
Written for <a href="http://stackoverflow.com/a/19911256/796832">this answer on StackOverflow</a>
<br /><br />

<form class="contact-form" method="post">
    First name: <input type="text" name="fname"><br>
    Last name: <input type="text" name="lname"><br>
    <input type="radio" name="sex" value="male">Male<br>
    <input type="radio" name="sex" value="female">Female<br>
    <input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
    <textarea id="the-textarea"></textarea><br>
    <input type="submit" value="Submit">
</form>
<div class="form-status-holder"></div>

JavaScript

var timeoutId;
$('form input, form 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');
    form = $('.contact-form');
	$.ajax({
		url: "/echo/json/",
		type: "POST",
		data: form.serialize(), // serializes the form's elements.
		beforeSend: function(xhr) {
            // Let them know we are saving
			$('.form-status-holder').html('Saving...');
		},
		success: function(data) {
			var jqObj = jQuery(data); // You can get data returned from your ajax call here. ex. jqObj.find('.returned-data').html()
            // Now show them we saved and when we did
            var d = new Date();
            $('.form-status-holder').html('Saved! Last: ' + d.toLocaleTimeString());
		},
	});
}

// This is just so we don't go anywhere  
// and still save if you submit the form
$('.contact-form').submit(function(e) {
	saveToDB();
	e.preventDefault();
});