Last active
September 6, 2017 02:07
-
-
Save brettbartylla/e452da89d8102f1e9640cfa7fa82ac82 to your computer and use it in GitHub Desktop.
Form submission using Ajax
This file contains 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
$(function() { | |
// Get the form. | |
var form = $('#ajax-contact'); | |
// Get the messages div. | |
var formMessages = $('#form-messages'); | |
// Set up an event listener for the contact form. | |
$(form).submit(function(e) { | |
// Stop the browser from submitting the form. | |
e.preventDefault(); | |
// Serialize the form data. | |
var formData = $(form).serialize(); | |
// Submit the form using AJAX. | |
$.ajax({ | |
type: 'POST', | |
url: $(form).attr('action'), | |
data: formData | |
}) | |
.done(function(response) { | |
// Make sure that the formMessages div has the 'success' class. | |
$(formMessages).removeClass('error'); | |
$(formMessages).addClass('success'); | |
// Set the message text. | |
$(formMessages).text(response); | |
// Clear the form. | |
$('#name').val(''); | |
$('#email').val(''); | |
$('#message').val(''); | |
}) | |
.fail(function(data) { | |
// Make sure that the formMessages div has the 'error' class. | |
$(formMessages).removeClass('success'); | |
$(formMessages).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.'); | |
} | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment