Skip to content

Instantly share code, notes, and snippets.

@bradley
Created April 24, 2012 21:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradley/2484138 to your computer and use it in GitHub Desktop.
Save bradley/2484138 to your computer and use it in GitHub Desktop.
Create new JS object for each input field and send AJAX call when user stops typing.
// =========== Input Field Listener with AJAX Callback ==============
function FieldListener(entity){
var t = this;
this.typingTimer; // Timer identifier
this.doneTypingInterval = 750; // Time in ms. e.g.; 5000 = 5secs
this.entity = entity;
this.noticeSpan = this.entity.siblings("span");
this.parentForm = entity.parents('form:first');
entity.on("keyup", function(){t.setTimer();});
}
FieldListener.prototype.setTimer = function(){
var t = this;
clearTimeout(this.typingTimer);
// Display 'waiting' notice to user.
this.noticeSpan.html('...')
this.typingTimer = setTimeout(function({
t.doneTyping();
},this.doneTypingInterval);
}
FieldListener.prototype.doneTyping = function(){
var t = this;
$.ajax({
url: '/some/path/',
type: "POST",
data: this.parentForm.serialize()
})
.done(function(validationMessage){
t.noticeSpan.html(validationMessage);
})
.fail(function(jqXHR, textStatus){
t.noticeSpan.html("Something went wrong. Please try again.");
});
}
var fieldListeners = [];
i = 0;
$(".update-user-info-field").each(function(){
fieldListeners[i] = new FieldListener($(this));
i++
});
// =========== /Input Field Listener with AJAX Callback =============
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment