Created
February 22, 2011 19:03
-
-
Save jakebellacera/839163 to your computer and use it in GitHub Desktop.
JQuery validate form that submits via AJAX
This file contains hidden or 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
/* | |
ajax-send.js - copyright Jake Bellacera (http://jakebellacera.com) | |
This script uses JQuery & JQuery Validate (https://github.com/jzaefferer/jquery-validation) | |
For this example, we will have a form named '#ajaxform', you can of course change this to whatever you'd like. | |
*/ | |
$(function(){ | |
$('#submitbutton').click(function() { | |
// validate and process form here | |
$('#mailform').validate({ | |
rules: { | |
// Set rules for special fields (email/phone?) | |
}, | |
// JQuery's awesome submit handler. | |
submitHandler(function(form) { | |
// Create variables from the form | |
var to = $('input#to').val(); | |
var fullname = $('input#fullname').val(); | |
var emailaddress = $('input#emailaddress').val(); | |
var message = $('textarea#message').val(); | |
// Create variables that will be sent in a URL string to mail.php | |
var dataString = 'to=' + to + '&fullname='+ fullname + '&emailaddress=' + emailaddress + '&message=' + message; | |
// The AJAX | |
$.ajax({ | |
type: 'POST', | |
url: '/path/to/mail.php', | |
data: dataString, | |
success(function(data) { | |
// This is a callback that runs if the submission was a success. | |
// Clear the form | |
$(':input','#mailform') | |
.not(':button, :submit, :reset, :hidden') | |
.val('') | |
.removeAttr('checked') | |
.removeAttr('selected'); | |
return false; | |
}), | |
error(function(){ | |
alert('Whoops! This didn\'t work. Please contact us.') | |
}); | |
}); | |
return false; | |
}); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good one