Integrate  Bootstrap Modal Popup Form and Submit  data to Email and MYSQL Database in PHP using Ajax

Integrate Bootstrap Modal Popup Form and Submit data to Email and MYSQL Database in PHP using Ajax

Table of contents

No heading

No headings in the article.

Below is how you can integrate a modal popup form to your website using Bootstrap and submit the form with jQuery, Ajax, and PHP.

For example, we’ll build a contact form with a Bootstrap modal popup and submit the form after validation using jQuery, Ajax, and PHP.

The following functionality will be implemented in the Bootstrap modal form script.

  • Modal popup with contact form using Bootstrap.

  • Validate form data before submitting using jQuery.

  • Submit form data with jQuery, Ajax, and PHP.

  • Send data to the MYSQL database and email address.

Bootstrap & jQuery Library

Bootstrap is used to create a modal popup and design an HTML form, (include the bootstrap and jQuery library first).

<!-- Latest minified bootstrap css -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<!-- Latest minified bootstrap js -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

HTML Code: Bootstrap Modal Popup Form

The following HTML creates a dialog popup window using bootstrap. A button is used to trigger this modal window and open a form for submitting the contact request. The button or link needs two data-* attributes, data-toggle="modal" and data-target="#modalForm". Also, the modal div must have an id attribute that should be the same as the data-target attribute of trigger link or button.

<!-- Button to trigger modal -->
<button class="btn btn-success btn-lg" data-toggle="modal" data-target="#modalForm">
    Click to open Contact Form
</button>

<!-- Modal -->
<div class="modal fade" id="modalForm" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <!-- Modal Header -->
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">
                    <span aria-hidden="true">&times;</span>
                    <span class="sr-only">Close</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">Contact Form</h4>
            </div>

            <!-- Modal Body -->
            <div class="modal-body">
                <p class="statusMsg"></p>
                <form role="form">
                    <div class="form-group">
                        <label for="inputName">Name</label>
                        <input type="text" class="form-control" id="inputName" placeholder="Enter your name"/>
                    </div>
                    <div class="form-group">
                        <label for="inputEmail">Email</label>
                        <input type="email" class="form-control" id="inputEmail" placeholder="Enter your email"/>
                    </div>
                    <div class="form-group">
                        <label for="inputMessage">Message</label>
                        <textarea class="form-control" id="inputMessage" placeholder="Enter your message"></textarea>
                    </div>
                </form>
            </div>

            <!-- Modal Footer -->
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary submitBtn" onclick="submitContactForm()">SUBMIT</button>
            </div>
        </div>
    </div>
</div>

JavaScript Code: Validate and Submit Form

The submitContactForm() function is triggered by clicking the form submit button. In the submitContactForm() function, popup form data is validated before submission and submitted to the submit_form.php file for further processing using jQuery and Ajax.

    <!--- Bootstrap Modal form validation File -->
    <script>
    function submitContactForm(){
        var reg = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
        var name = $('#inputName').val();
        var email = $('#inputEmail').val();
        var message = $('#inputMessage').val();
        if(name.trim() == '' ){
            alert('Please enter your name.');
            $('#inputName').focus();
            return false;
        }else if(email.trim() == '' ){
            alert('Please enter your email.');
            $('#inputEmail').focus();
            return false;
        }else if(email.trim() != '' && !reg.test(email)){
            alert('Please enter valid email.');
            $('#inputEmail').focus();
            return false;
        }else if(message.trim() == '' ){
            alert('Please enter your message.');
            $('#inputMessage').focus();
            return false;
        }else{
            $.ajax({
                type:'POST',
                url:'submit_form.php',
                data:'contactFrmSubmit=1&name='+name+'&email='+email+'&message='+message,
                beforeSend: function () {
                    $('.submitBtn').attr("disabled","disabled");
                    $('.modal-body').css('opacity', '.5');
                },
                success:function(msg){
                    if(msg == 'ok'){
                        $('#inputName').val('');
                        $('#inputEmail').val('');
                        $('#inputMessage').val('');
                        $('.statusMsg').html('<span style="color:green;">Thanks for contacting us, we\'ll get back to you soon.</p>');
                    }else{
                        $('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
                    }
                    $('.submitBtn').removeAttr("disabled");
                    $('.modal-body').css('opacity', '');
                }
            });
        }
    }
    </script>

Send data to the MYSQL database and email address (submit_form.php)

In the submit_form.php file, the following codes below are for processing the form submit request.

  • Check whether the submitted form is not empty and validate the email by FILTER_VALIDATE_EMAIL filter in PHP.

  • Get the form data using PHP $_POST method.

  • Send HTML email with contact details to site admin using PHP mail() function.

Once the required action is completed, the status message is rendered that would be used by the Ajax success method.


<?php
$servername = "insert your servername";
$username = " insert your username";
$password = "insert your password";
$dbname = "insert your database name";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}

// Escape user inputs for security
$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$message = mysqli_real_escape_string($conn, $_POST['message']);

// Insert  into database

$sql = "INSERT INTO tableName (name, email, message) VALUES ('$name', '$email', '$message' )";

use PHPMailer\PHPMailer\PHPMailer; // Phpmail package already on server
use PHPMailer\PHPMailer\Exception; // Phpmail package already on server

require 'PHPMailer/src/PHPMailer.php'; // Phpmail package already on server
require 'PHPMailer/src/SMTP.php'; // Phpmail package already on server

$mail = new PHPMailer();

$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "localhost"; // sets the SMTP server or use the server hostname
$mail->Port = 25; // set the SMTP port for the GMAIL server
$mail->Username = "companymail@company.com"; // SMTP account username
$mail->Password = "mail password here"; // SMTP account password

$mail->SetFrom('companymail@company.com');
$mail->AddReplyTo("companymail@company.com");
$mail->Subject = "Contact form submitted";
$mail->MsgHTML("<html><body><em>Below is the details of the new record! </em><br><br><br><strong>Name:</strong> $name,<br><br><strong>Email:</strong> $email,<br><br><strong>Message:</strong> $message</body></html>");

$mail->AddAddress("companymail@company.com");
//$mail->AddAttachment(""); // attachment

//If the form is submitted successfully
if (!$mail->Send()){

} elseif (mysqli_query($conn, $sql)){

}
?>


}
mysqli_close($conn);




// Close connection

?>