Skip to content

Instantly share code, notes, and snippets.

@lucasrodriguex
Created May 23, 2016 03:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucasrodriguex/200e228d6b285ece7f24e9d2d2f1a524 to your computer and use it in GitHub Desktop.
Save lucasrodriguex/200e228d6b285ece7f24e9d2d2f1a524 to your computer and use it in GitHub Desktop.
Generic ajax for html forms
$(document).ready( function () {
// I only have one form on the page but you can be more specific if need be.
var $form = $('form');
if ( $form.length > 0 ) {
$('form input[type="submit"]').bind('click', function ( event ) {
if ( event ) event.preventDefault();
// validate_input() is a validation function I wrote, you'll have to substitute this with your own.
if ( validate_input($form) ) { register($form); }
});
}
});
function register($form) {
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'json',
contentType: "application/json; charset=utf-8",
error : function(err) { alert("Could not connect to the registration server. Please try again later."); },
success : function(data) {
if (data.result != "success") {
// Something went wrong, do something to notify the user. maybe alert(data.msg);
} else {
// It worked, carry on...
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment