Instantly share code, notes, and snippets.

What would you like to do?
Ajax Contact Form Resource
PHP Code:
// Only process POST reqeusts.
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$lname = trim($_POST["lname"]);
$subject = trim($_POST["subject"]);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($subject) OR empty($lname) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
echo "Please complete the form and try again.";
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "First Name: $name\n";
$email_content = "Last Name: $lname\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Subject: $subject\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
echo "Oops! Something went wrong and we couldn't send your message.";
} else {
// Not a POST request, set a 403 (forbidden) response code.
echo "There was a problem with your submission, please try again.";
Ajax jQuery
$(function() {
// Get the form.
var form = $('#contact-form');
// Get the messages div.
var formMessages = $('.form-message');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
type: 'POST',
url: $(form).attr('action'),
data: formData
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
// Set the message text.
// Clear the form.
$('#contact-form input,#contact-form textarea').val('');
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
// Set the message text.
if (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