In this Post we will see how to create a contact form with using jquery Ajax and PHP and also insert contact form data in database table.
The PHP AJAX contact form is used to send contact information to the back end without refreshing the page. We have provided sample contact forms to collect user requests, feedback, etc. After validation by the client, data from this form is sent to the PHP page via the jQuery AJAX call. After sending the contact email, the PHP page respond to the AJAX request.
we will also insert the contact form data in database table. It’s your choice if you want to sent user feedback message into database. So, you can use the otherwise ignore this. Because In this post we will send mail using localhost with PHPMailer with SMTP.
If you want to learn How to configure SMTP server to Send Email using PHP ?
Created Database Configuration File
In this step, we require to create database configuration file, here we will set database name, username and password. So let’s create dbconfig.php file on your root directory and put bellow code:
If you want to insert contact form or feedback data in database table. So, that you need to create database connection file.
<?php // Database configuration $dbHost = "localhost"; $dbUsername = "root"; $dbPassword = ""; $dbName = "registration"; // Create database connection $con = mysqli_connect($dbHost, $dbUsername, $dbPassword, $dbName); // Check connection if ($con->connect_error) { die("Connection failed: " . $con->connect_error); } ?>
Create HTML page for Contact form
This contact form contains a collection of data for user feedback. It triggers an AJAX jQuery call when the “Send Message” button is clicked.
index.php
<!Doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Contact form with validation in PHP mailer jquery Ajax script</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> </head> <body> <div class="container" style="margin-top:50px"> <h1 style="text-align:center;">Contact form with validation in PHP mailer jquery Ajax script</h1><br> <div class="row"> <div class="col-md-3"></div> <div class="col-md-6"> <div class="alert alert-success alert-dismissible success" style="display: none;"> <button type="button" class="close" data-dismiss="alert">×</button> <span id="success"></span> </div> <div class="alert alert-danger alert-dismissible danger" style="display: none;"> <button type="button" class="close" data-dismiss="alert">×</button> <span id="danger"></span> </div> <form id="contactForm"> <div class="form-group"> <input type="text" class="form-control" id="name" placeholder="Name"> </div> <div class="form-group"> <input type="email" class="form-control" id="email" placeholder="Email"> </div> <div class="form-group"> <input type="text" class="form-control" id="subject" placeholder="Subject"> </div> <div class="form-group"> <textarea rows="5" class="form-control" id="message" placeholder="Message"></textarea> </div> <div class="form-group"> <button type="submit" class="btn btn-success btn btn-block" id="btnSubmit">Send Message</button> </div> </form> </div> </div> </div> </body> </html>
jQuery AJAX Contact form Mail Sending Event Handler
This jQuery script validate contact form data and, after successful verification, sends an AJAX request to the PHP page. It collects contact form data and sends them as parameters to the second page of PHP.
<script type="text/javascript"> $(document).ready(function(){ $("#contactForm").on("submit",function(e){ e.preventDefault(); var name = $("#name").val(); var email = $("#email").val(); var subject = $("#subject").val(); var message = $("#message").val(); if(name == "") { $("#danger").text("Name is required"); $(".danger").show(); }else if (email == "") { $("#danger").text("Email is required"); $(".danger").show(); }else if (subject == "") { $("#danger").text("Subject is required"); $(".danger").show(); }else if (message == "") { $("#danger").text("Message is required"); $(".danger").show(); }else{ $.ajax({ url : "contacts.php", type : "POST", cache:false, data :{name:name,email:email,subject:subject,message:message}, success:function(response){ $("#success").text("Contact form submitted successfully"); $(".success").show(); $(".danger").hide(); $("#contactForm").trigger('reset'); } }); } }); }); </script>
Create PHP code for sending contact mail
In this page we will create the PHP code to send the data in database table and also send HTML email from localhost to PHP using PHPMailer. Download PHPMailer files from Github.
If you want to learn How to configure SMTP server to Send Email using PHP ?. In this post I am explain step by step.
contacts.php
<?php // Include database connection file include_once('dbconfig.php'); if (isset($_POST['email'])) { $name = strip_tags(trim($_POST["name"])); $name = str_replace(array("\r","\n"),array(" "," "), $name); $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL); $subject = trim($_POST["subject"]); $message = trim($_POST["message"]); $query = "INSERT INTO contacts (name, email, subject, message) VALUES('$name','$email','$subject','$message')"; $result = mysqli_query($con, $query); if ($result==true) { sendMail($email, ucwords($subject),$message); }else{ return false; } } // Create PHPMailder function for sent mail function sendMail($to, $subject, $message){ require 'PHPMailer/PHPMailerAutoload.php'; $mail = new PHPMailer(true); $mail->SMTPDebug = 3; // Enable verbose debug output $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = 'YourEmailAddress'; // SMTP username $mail->Password = 'YourEmailPassword'; // SMTP password $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted $mail->Port = 587; // TCP port to connect to $mail->setFrom($to, 'Contact us'); $mail->addAddress('YourEmailAddress', 'Contact us'); // Add a recipient $mail->addAddress('YourEmailAddress'); // Name is optional $mail->addReplyTo($to, 'Contact us'); // Add reply to users $mail->isHTML(true); // Set email format to HTML $mail->SMTPOptions = array( 'ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true ) ); $mail->Subject = $subject; $mail->Body = $message; if($mail->send()) { return true; } else { return false; } } ?>
Output

You can always support by sharing on social media or recommending my blog to your friends and colleagues. If you have any suggestions / problems about this tutorial, please comment on the form below.😊
you are not doing server side validation