Skip to content

Instantly share code, notes, and snippets.

@dmgig
Last active August 29, 2015 14:14
Show Gist options
  • Save dmgig/c0b0aa78eb6c1ac8fdd0 to your computer and use it in GitHub Desktop.
Save dmgig/c0b0aa78eb6c1ac8fdd0 to your computer and use it in GitHub Desktop.
Auto-saving Form (jQuery required)
/**
* editBox
* auto-updating form, with reset/resave
* @author D.M. Giglio
*/
(function(window, document, $){
'use strict';
$(document).ready(function(){
var editBox;
editBox = {
form : $('form#input_form'),
// selectors and actions to update on
onactions : [
{ selector : 'input[type=text]', action : 'keyup' },
{ selector : 'input[type=checkbox]', action : 'click' },
{ selector : 'select', action : 'change' }
],
intent_time : 450,
update_url : 'apply_changes2.0.php',
data : function () { return editBox.form.serialize(); },
origdata : function () { editBox.form.serialize(); },
timer : 0,
ajax : null,
// initialize
init : function () {
console.log('init');
editBox.onactions.forEach(function(n){
$(n.selector).on(n.action, function(e){ editBox.delayedJAX(e); });
});
$('input[name=reset]').on('click', function(){ editBox.reset(); });
},
// main update function
// calls updateDelay after making checks about which buttons were keyed
delayedJAX : function (e) {
try{
if(e.which == 9) { return; } // exclude tab
}catch(err){ }
editBox.updateDelay();
},
// add an intent delay onto the update script.
// more changes reset the timer.
updateDelay : function () {
editBox.form.addClass('saving');
clearTimeout(editBox.timer);
editBox.timer = setTimeout(function() {
editBox.ajaxUpdate();
}, editBox.intent_time);
},
// actual ajax update
ajaxUpdate : function () {
var ajax_opts;
ajax_opts = {
type : 'POST',
url : editBox.update_url,
dataType : 'json',
data : editBox.data()
};
editBox.ajax = $.ajax(ajax_opts);
editBox.ajax.done( function(data) {
if(data.result === 'success'){
console.log('success');
editBox.updateSuccess(data);
}else{
alert('Error: Could not save your data. ' + data.error);
location.reload();
}
});
editBox.ajax.always(function() { editBox.form.removeClass('saving'); });
},
// on ajax done success
updateSuccess : function (data) {
if(typeof data.response.person !== 'undefined'){
$('input[name=person_id]').val(data.response.person.id);
}
if(typeof data.response.address !== 'undefined'){
$('input[name=address_id]').val(data.response.address.id);
}
},
// reset form, and re-save original values
reset : function () {
editBox.form[0].reset();
editBox.delayedJAX(null);
}
};
editBox.init();
});
})(window, document, jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment