Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save markhillard/b3d87c362f9a9e53180b1b184e2d25b6 to your computer and use it in GitHub Desktop.
Save markhillard/b3d87c362f9a9e53180b1b184e2d25b6 to your computer and use it in GitHub Desktop.
AJAX Form Submission Using jQuery

AJAX Form Submission Using jQuery

This is a simple contact form with built-in email validation, input field behaviors and an AJAX submission handler. The page will not refresh when the form is submitted, which allows for custom UI functions. In this example, the data will be posted in the background to a mail form file.

Use the console in your browser's developer tools to see the form in action.

A Pen by Mark Hillard on CodePen.

License.

<div id="container">
<form method="post" action="mail.mf">
<input type="text" value="Name">
<input type="email" pattern="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?" value="Email Address" required>
<textarea>Comments / Questions?</textarea>
<button type="submit">Submit</button>
<button type="reset">Reset</button>
<div class="invalid">Invalid Email!</div>
<div class="success">Email Sent!</div>
<div class="error">Error!</div>
<div class="reset">Reset!</div>
</form>
</div>
/*! Contact Form Behaviors */
$(document).ready(function () {
$('button[type="submit"]').click(function (e) {
// prevent default action and bubbling
e.preventDefault();
e.stopPropagation();
// email validation variables (regex)
var filter = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g;
var error = false;
// variables for input field values
var name = $('input[type="text"]').val();
var address = $('input[type="email"]').val();
var message = $('textarea').val();
// if email is invalid... *
if (!filter.test(address)) {
// * show invalid message and hide others
$('.invalid').show().delay(2000).fadeOut(300);
$('.success, .error, .reset').hide();
// * focus on email field
$('input[type="email"]').focus();
// * set error status
error = true;
// if email is valid... *
} else {
// * variable for "mail.mf" file
var formURL = $('form').attr('action');
// * post data to "mail.mf" file
var postData = 'name=' + name + '&email=' + address + '&message=' + message;
// * ajax form submission handler
$.ajax({
type: 'POST',
url: formURL,
data: postData,
success: function (data, responseText) {
// reset original field values
$('input[type="text"]').val('Name');
$('input[type="email"]').val('Email Address');
$('textarea').val('Comments / Questions?');
// show success message and hide others
$('.success').show().delay(2000).fadeOut(300);
$('.invalid, .error, .reset').hide();
},
error: function (errorThrown) {
// show error message and hide others
$('.error').show().delay(2000).fadeOut(300);
$('.invalid, .success, .reset').hide();
// log error message in console
console.log(errorThrown);
}
});
}
});
// clear default input field values and return on blur event
$('input, textarea').focus(function () {
if (!$(this).data('default')) {
$(this).data('default', $(this).val());
}
if ($(this).val() !== '' && $(this).val() === $(this).data('default')) {
$(this).val('');
}
}).blur(function () {
if ($(this).val() === '') {
$(this).val($(this).data('default'));
}
});
// force lowercase email address on change event
$('input[type="email"]').change(function () {
$(this).val($(this).val().toLowerCase());
});
// show reset message and hide others
$('button[type="reset"]').click(function () {
$('.reset').show().delay(2000).fadeOut(300);
$('.invalid, .success, .error').hide();
});
});
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
@import url("//fonts.googleapis.com/css?family=Titillium+Web");
html,body {
background-color:#666;
font-family:"Titillium Web", arial, sans-serif;
margin:0;
padding:0;
}
*,*::before,*::after { box-sizing:border-box; }
*:focus { outline:none; }
button,input,textarea { appearance:none; background:none; }
button::-moz-focus-inner,input::-moz-focus-inner { border:0; padding:0; }
#container { display:block; width:436px; }
form {
float:left;
margin:31px 0 0 31px;
overflow:auto;
padding-bottom:13px;
position:relative;
}
button[type="submit"],button[type="reset"] {
background-color:#333;
border:none;
border-radius:5px;
color:#aaa;
cursor:pointer;
float:right;
font-family:"Titillium Web", arial, sans-serif;
font-size:21px;
font-weight:400;
margin:10px 0 0 15px;
padding:5px 20px;
text-decoration:none;
transition:all 160ms linear;
}
button[type="submit"]:hover,button[type="reset"]:hover { background-color:#222; }
input[type="text"],input[type="email"] {
background-color:#333 !important;
border:none;
border-radius:5px;
color:#aaa;
font-family:"Titillium Web", arial, sans-serif;
font-size:16px;
font-weight:400;
height:43px;
margin:0 0 14px;
overflow:auto;
padding:8px 0 8px 13px;
width:416px;
}
input[type="email"]:required:invalid,input[type="email"]:focus:invalid {
background-image:url("http://www.markhillard.com/images/lock.svg");
background-position:right 8px center;
background-repeat:no-repeat;
background-size:23px 23px;
box-shadow:none;
}
input[type="email"]:required:valid,input[type="email"]:focus:valid {
background-image:url("http://www.markhillard.com/images/unlock.svg");
background-position:right 8px center;
background-repeat:no-repeat;
background-size:23px 23px;
}
textarea {
background-color:#333;
border:none;
border-radius:5px;
clear:left;
color:#aaa;
display:block;
float:left;
font-family:"Titillium Web", arial, sans-serif;
font-size:16px;
font-weight:400;
height:241px;
margin:0 0 4px;
overflow:auto;
padding:8px 0 8px 13px;
resize:none;
width:416px;
}
.invalid,.success,.error,.reset {
display:none;
float:left;
margin:9px 0 0 13px;
position:absolute;
top:360px;
}
.invalid,.error { color:#f5b2b6; }
.success,.reset { color:#d7f5b2; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment