Created
May 23, 2016 03:11
-
-
Save lucasrodriguex/200e228d6b285ece7f24e9d2d2f1a524 to your computer and use it in GitHub Desktop.
Generic ajax for html forms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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