Skip to content

Instantly share code, notes, and snippets.

@MarcosBL
Last active December 20, 2015 20:09
Show Gist options
  • Save MarcosBL/6188408 to your computer and use it in GitHub Desktop.
Save MarcosBL/6188408 to your computer and use it in GitHub Desktop.
Simple AJAX form controller with jQuery. It takes care of AJAX stuff, cache busting, avoiding double submit, visual clues and returning values in a few lines of code. You can check it live at http://marcosbl.com/gifsound/?#new
$(document).ready(function(){
$('form[data-async]').on('submit', function(event) {
var $form = $(this);
$form.find('input[type="submit"],button[type="submit"]').each(function() {
$(this).attr("disabled","disabled").addClass($(this).attr("data-processing-class")).attr("data-original-text",$(this).html()).html($(this).attr("data-processing"));
});
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
cache: $form.attr('data-cache'),
data: $form.serialize(),
success: function(data, status) {
$($form.attr('data-target')).html(data);
},
error: function(data, status) {
(data.responseText)?$($form.attr('data-target')).html(data.responseText):alert("Error happened");
console.log(data);
$form.find('input[type="submit"],button[type="submit"]').each(function() {
$(this).attr("disabled",false).removeClass($(this).attr("data-processing-class")).html($(this).attr("data-original-text"));
});
},
});
event.preventDefault();
});
});
<form method="POST" data-async data-target=".result_div" data-cache="false" action="/process">
<input type="text" id="field1" name="field1" placeholder="Field 1">
<input type="text" id="field2" name="field2" placeholder="Field 2">
<button type="submit" data-processing="¡ OK, SENDING !" data-processing-class="btn-warning" class="btn">¡ Go !</button>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment