Skip to content

Instantly share code, notes, and snippets.

@jenhuls
Last active January 18, 2022 12:12
Show Gist options
  • Save jenhuls/4d99288b9d9e06fd73f81675bfeee975 to your computer and use it in GitHub Desktop.
Save jenhuls/4d99288b9d9e06fd73f81675bfeee975 to your computer and use it in GitHub Desktop.
[PHP Contact Form w/ AJAX] #jquery #php #html
<div class="contact container shadow" id="contact_form">
<div class="contact row header">
<h2>CONTACT US</h2>
<h3>Request information, book a studio, or plan your event!</h3>
<div id="contact_results"></div>
</div>
<div class="contact row body" id="contact_body">
<div class="contact-elements">
<ul>
<li>
<p class="left">
<label for="name">name</label>
<input type="text" name="name" id="name" required="true" class="input-field" placeholder="Jane Doe" />
</p>
<p class="pull-right">
<label for="phone2">phone</label>
<input type="text" name="phone2" maxlength="15" class="tel-number-field long" placeholder="123 456 7890" />
</p>
</li>
<div class="center-btn" style="position:relevant; height:5vh;">
<li>
<label for="email">email <span class="req">*</span></label>
<input type="email" name="email" required="true" class="input-field" placeholder="[email protected]" />
</li>
</div>
<li>
<div class="contact divider"></div>
</li>
<li>
<label for="message">enquiry</label>
<textarea cols="46" rows="8" name="message" id="message" class="textarea-field" required="true"></textarea>
</li>
</ul>
</div>
<div class="center-btn" style="position:relevant; height:5vh;">
<li>
<input id="submit_btn" class="btn btn-submit" type="submit" value="Submit" />
</li>
</div>
</div>
</div>
<?php
if($_POST)
{
$to_email = "[email protected]"; //Recipient email, Replace with own email here
$subject = "Form Submission from YOURWEBSITE.COM";
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$user_name = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING);
$user_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
$phone_number = filter_var($_POST["phone_number"], FILTER_SANITIZE_NUMBER_INT);
$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
//additional php validation
if(strlen($user_name)<4){ // If length is less than 4 it will output JSON error.
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty'));
die($output);
}
if(!filter_var($user_email, FILTER_VALIDATE_EMAIL)){ //email validation
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email'));
die($output);
}
if(!filter_var($phone_number, FILTER_SANITIZE_NUMBER_FLOAT)){ //check for valid numbers in phone number field
$output = json_encode(array('type'=>'error', 'text' => 'Enter only digits in phone number'));
die($output);
}
if(strlen($message)<3){ //check emtpy message
$output = json_encode(array('type'=>'error', 'text' => 'You forgot the most important part..'));
die($output);
}
//email body
$headers = "From: " . $user_email . "\r\n";
$headers .= "Reply-To: ". $user_email . "\r\n";
// $headers .= "CC: " . $carbonCopy . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message_body = "<html><body>";
$message_body .= "<p>Full Name: " . $user_name . "</p>";
$message_body .= "<p>Email Address: " . $user_email . "</p>";
$message_body .= "<p>Phone No.: " . $phone_number . "</p>";
$message_body .= "<p>Message: " . $message . "</p>";
$message_body .= "</body></html>";
$send_mail = mail($to_email, $subject, $message_body, $headers);
if(!$send_mail)
{
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_name .' We will reply as soon as possible!'));
die($output);
}
}
$(document).ready(function() {
$("#submit_btn").click(function() {
var proceed = true;
//simple validation at client's end
//loop through each field and we simply change border color to red for invalid fields
$("#contact_form input[required=true], #contact_form textarea[required=true]").each(function() {
$(this).css('border-color', '');
if (!$.trim($(this).val())) { //if this field is empty
$(this).css('border-color', 'red'); //change border color to red
proceed = false; //set do not proceed flag
}
//check invalid email
var email_reg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if ($(this).attr("type") == "email" && !email_reg.test($.trim($(this).val()))) {
$(this).css('border-color', 'red'); //change border color to red
proceed = false; //set do not proceed flag
}
});
if (proceed) //everything looks good! proceed...
{
//get input field values data to be sent to server
post_data = {
'user_name': $('input[name=name]').val(),
'user_email': $('input[name=email]').val(),
'phone_number': $('input[name=phone2]').val(),
'msg': $('textarea[name=message]').val()
};
//Ajax post data to server
$.post('inc/form_process.php', post_data, function(response) {
if (response.type == 'error') { //load json data from server and output message
output = '<div class="error">' + response.text + '</div>';
} else {
output = '<div class="success">' + response.text + '</div>';
//reset values in all input fields
$("#contact_form input[required=true], #contact_form textarea[required=true]").val('');
$("#contact_form #contact_body").slideUp(); //hide form after success
}
$("#contact_form #contact_results").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input[required=true], #contact_form textarea[required=true]").keyup(function() {
$(this).css('border-color', '');
$("#result").slideUp();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment