Skip to content

Instantly share code, notes, and snippets.

@EastSideCode
Created November 13, 2017 20:38
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 EastSideCode/4ac9c7cdb551d8714d5dea3e5c711802 to your computer and use it in GitHub Desktop.
Save EastSideCode/4ac9c7cdb551d8714d5dea3e5c711802 to your computer and use it in GitHub Desktop.
Generic, reusable, AJAX Mailer
jQuery(document).ready(function($) {
// load form elements in vars for ease of use
var frm = $('#contact-form');
var formMessages = $('#form-messages');
var loadingAnimation = $('#loading-container');
frm.submit(function (e) {
e.preventDefault();
// prevent spam with honeypot
if ($('input#honeypot').val().length != 0) {
console.log("spam message");
return false;
}
$.ajax({
type: "POST",
url: frm.attr('action'),
data: frm.serialize(),
beforeSend: function() {
// while sending, show an ajax spinner and fade the form out a little
loadingAnimation.show();
frm.addClass('form-faded');
},
success: function (data) {
// Set the message text.
$(formMessages).text(data);
// add and remove classes for CSS styling
$(formMessages).removeClass('error').addClass('success');
// clear form fields
frm[0].reset();
},
error: function (data) {
// add and remove classes for CSS styling
$(formMessages).removeClass('success').addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
},
complete: function () {
// hide ajax spinner
loadingAnimation.hide();
frm.removeClass('form-faded');
}
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment