Skip to content

Instantly share code, notes, and snippets.

@nicekiwi
Last active December 26, 2015 10:30
Show Gist options
  • Save nicekiwi/295533d5d445dc17ac25 to your computer and use it in GitHub Desktop.
Save nicekiwi/295533d5d445dc17ac25 to your computer and use it in GitHub Desktop.
Code to power the frontend of my blogs Contact Form
$(document).ready(function () {
$('#contactForm').on('submit', function(event) {
// stop form submitting
event.preventDefault();
var form = $(this);
var button = form.find('button');
var responseBox = $('.response', form);
var success = function(response) {
if(!response.sent) {
failure();
return;
}
responseBox
.addClass('success')
.text('Yus! Your message has been sent. :)')
.show();
}
var failure = function() {
responseBox
.addClass('failure')
.text('Uh oh, Your Message could not be sent. Please try again.')
.show();
}
var always = function() {
// reset the form
form[0].reset();
// reset and hide the response message
setTimeout(function() {
responseBox
.removeClass('success')
.removeClass('failure')
.text('')
.hide();
// enable the send button
button.prop('disabled', false);
}, 10000);
}
// disable the send button to prevent spamming
button.prop('disabled', true);
// check if the just testing checkbox is checked. if true, actually submit
// a request, else just show the form looking pretty. You can remove this check.
if($('.justTesting', form).is(":checked")) {
success({ sent: true });
always();
} else {
// send message
// the apiDomain variable should be set before includeing this file
// <script>var apiDomain = 'YOUR_DOMAIN_HERE';</script>
//
$.post(apiDomain, form.serialize())
.done(success)
.fail(failure)
.always(always);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment