Build a Contact Us Form using PHP, AJAX and jQuery
The Contact Us form allows users to communicate with web application administrator. It allows them to send queries to the web application owners about relevant services. In this tutorial, we will learn how to Build a Simple Contact Us Form using PHP, AJAX and jQuery. We will cover this tutorial in easy steps with live demo to Contact Us Form in PHP.
So let’s implement Build a Contact Us Form using PHP. look following folder and file structure:
- build-contact-us-form-using-php-ajax-jquery
- assets
- css
- style.css
- js
- ajax.js
- css
- templates
- header.php
- footer.php
- index.php
- contactus.php
- assets
Step 1: Creating a Simple HTML Contact Form
Now in index.php, we will disign Bootstrap contact form
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
<?php include('templates/header.php');?> <section class="showcase"> <div class="container"> <div class="pb-2 mt-4 mb-2 border-bottom"> <h2>Build a Contact Form using PHP, AJAX and jQuery</h2> </div> <form id="contact-frm" class="contact-frm"> <div class="row"> <div class="col-md-3"> <div class="contact-info"> <i class="fa fa-envelope" style="font-size: 100px;" aria-hidden="true"></i> <h2>Contact Us</h2> <h4>We would love to hear from you !</h4> </div> </div> <div class="col-md-9"> <span id="sent-msg"></span> <div class="contact-form"> <div class="form-group"> <label class="control-label col-sm-2" for="fname">First Name:</label> <div class="col-sm-10"> <input type="text" class="form-control input-contact-firstname" id="fname" placeholder="Enter first name" name="firstname"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="lname">Last Name:</label> <div class="col-sm-10"> <input type="text" class="form-control input-contact-lastname" id="lname" placeholder="Enter last name" name="lastname"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="email">Email:</label> <div class="col-sm-10"> <input type="email" class="form-control input-contact-email" id="email" placeholder="Enter email" name="email"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="comment">Comment:</label> <div class="col-sm-10"> <textarea class="form-control input-contact-comment" rows="5" id="comment" placeholder="Comment" name="comment"></textarea> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="button" class="btn btn-default custom-button float-right" id="visitor-contact">Submit</button> </div> </div> </div> </div> </div> </form> </div> </section> <?php include('templates/footer.php');?> |
Step 2: Handle jQuery Ajax Contact Form Submit
In ajax.js, we will handle contact form submit with jQuery Ajax to not reload page when submit form. Send Ajax request to contactus.php to send contact page detail email with form validation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
jQuery(document).on('click', 'button#visitor-contact', function(){ jQuery.ajax({ type:'POST', url:'contactus.php', data:jQuery("form#contact-frm").serialize(), dataType:'json', beforeSend: function () { jQuery('button#visitor-contact').button('loading'); }, complete: function () { jQuery('button#visitor-contact').button('reset'); jQuery('#contact-frm').find('textarea, input').each(function () { jQuery(this).val(''); }); setTimeout(function () { jQuery('span#sent-msg').html(''); }, 7000); }, success: function (json) { jQuery('.text-danger').remove(); if (json['error']) { for (i in json['error']) { var element = jQuery('.input-contact-' + i.replace('_', '-')); if (jQuery(element).parent().hasClass('input-group')) { jQuery(element).parent().after('<div class="text-danger" style="font-size: 14px;">' + json['error'][i] + '</div>'); } else { jQuery(element).after('<div class="text-danger" style="font-size: 14px;">' + json['error'][i] + '</div>'); } } } else { if(json.type=='message') { jQuery('span#sent-msg').html('<div class="alert alert-success alert-dismissible"><button type="button" class="close" data-dismiss="alert">×</button><strong>Success!</strong>'+json.text+'</div>'); } else { jQuery('span#sent-msg').html('<div class="alert alert-danger alert-dismissible"><button type="button" class="close" data-dismiss="alert">×</button><strong>Error!</strong> '+json.text+'</div>'); } } }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }); |
Step 3: Send Contact Form Details
Now finally in contactus.php, User fill the conatct us form and clicks on send button, following php code will executes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
<?php // array $json = array(); // POST $post = $_POST; $first_name = filter_var($post["firstname"], FILTER_SANITIZE_STRING); $last_name = filter_var($post["lastname"], FILTER_SANITIZE_STRING); $email = filter_var($post["email"], FILTER_SANITIZE_EMAIL); $comment = filter_var($post["comment"], FILTER_SANITIZE_STRING); // first name validation if(empty(trim($first_name))){ $json['error']['firstname'] = 'Please enter first name'; } // first name validation if(empty(trim($last_name))){ $json['error']['lastname'] = 'Please enter last name'; } // email validation if(empty(trim($email))){ $json['error']['email'] = 'Please enter email address'; } // check email validation if (validateEmail($email) == FALSE) { $json['error']['email'] = 'Please enter valid email address'; } // comment validation if(empty($comment)){ $json['error']['comment'] = 'Please enter comment'; } // send if(empty($json['error'])) { $toEmail = "contact@webhaunt.com"; $mailHeaders = "From: " . $first_name . "<" . $email . ">\r\n"; $mailBody = "Visitor Name: " . $first_name .' '. $last_name . "\n"; $mailBody .= "Visitor Email: " . $email . "\n"; $mailBody .= "Visitor comment: " . $comment . "\n"; if (mail($toEmail, "Contact Mail", $mailBody, $mailHeaders)) { echo $json = json_encode(array('type'=>'message', 'text' => 'Hi '.$first_name .', thank you for the comments. We will get back to you shortly.')); } else { echo $json = json_encode(array('type'=>'error', 'text' => 'Unable to send email, please contact '.$toEmail)); } } else { echo json_encode($json); } // email validation function validateEmail($email) { return preg_match('/^[^\@]+@.*.[a-z]{2,15}$/i', $email)?TRUE:FALSE; } ?> |
Create
header.php
and footer.php
section of the webpage. The Bootstrap and jQuery library is used to provide a better UI, so, include it in the header and footer section.header.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<!DOCTYPE html> <html lang="en"> <head> <link rel="canonical" href="https://www.webhaunt.com/" /> <meta name="author" content="WebHaunt"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="https://webhaunt.com/wp-content/uploads/2016/11/webhaunt-150x142.png" sizes="32x32" /> <link rel="icon" href="https://webhaunt.com/wp-content/uploads/2016/11/webhaunt.png" sizes="192x192" /> <link rel="apple-touch-icon-precomposed" href="https://webhaunt.com/wp-content/uploads/2016/11/webhaunt.png" /> <meta name="msapplication-TileImage" content="https://webhaunt.com/wp-content/uploads/2016/11/webhaunt.png" /> <title>Build a Contact Form using PHP, AJAX and jQuery | Web Haunt</title> <!-- Bootstrap core CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" /> <!-- Custom fonts for this template --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.7.2/css/all.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.css" /> <link href="https://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css"> <!-- Custom styles for this template --> <link href="assets/css/style.css" rel="stylesheet"> <link href="assets/css/contact.css" rel="stylesheet"> </head> <body> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top header-bg-dark" style="background: ##FFFFFF!;"> <div class="container"> <a class="navbar-brand font-weight-bold" href="https://webhaunt.com"><h1>Web Haunt</h1></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="https://webhaunt.com/">Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="https://webhaunt.com/php-script-free-demo/">LIVE DEMO</a> </li> </ul> </div> </div> </nav> |
footer.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
<!-- Footer --> <footer class="footer bg-light footer-bg-dark"> <div class="container"> <div class="row"> <div class="col-lg-6 h-100 text-center text-lg-left my-auto"> <ul class="list-inline mb-2"> <li class="list-inline-item"> <a href="#">About</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Contact</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Terms of Use</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Privacy Policy</a> </li> </ul> <p class="small mb-4 mb-lg-0" style="color: #E6ECF0;">Copyright © 2017 - <?php print date('Y', time());?> <a style="color: #E6ECF0;" href="https://webhaunt.com/">WEBHAUNT.COM</a> All rights reserved.</p> </div> <div class="col-lg-6 h-100 text-center text-lg-right my-auto"> <ul class="list-inline mb-0"> <li class="list-inline-item mr-3"> <a href="#"> <i class="fab fa-facebook fa-2x fa-fw"></i> </a> </li> <li class="list-inline-item mr-3"> <a href="#"> <i class="fab fa-twitter-square fa-2x fa-fw"></i> </a> </li> <li class="list-inline-item"> <a href="#"> <i class="fab fa-instagram fa-2x fa-fw"></i> </a> </li> </ul> </div> </div> </div> </footer> <!-- Bootstrap core JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script> <script src="assets/js/ajax.js"></script> </body> </html> |