Skip to content

Instantly share code, notes, and snippets.

@jakebellacera
Created February 22, 2011 19:03
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jakebellacera/839163 to your computer and use it in GitHub Desktop.
Save jakebellacera/839163 to your computer and use it in GitHub Desktop.
JQuery validate form that submits via AJAX
/*
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;
});
});
});
});
@wackyapps
Copy link

Good one

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment