PHP

How to show Bootstrap Modal Popup as Alert box in PHP

Ravindra Kumar

Showing modal Popup in PHP as Alert Message Box

In this post, I am going to explain about showing a popup message box using bootstrap modal popup in PHP. In this post i am going to use PHP, JavaScript, Ajax and bootstrap. First I need to create a form where the user can fill the data and this data will be sent to specified email address and after sending the data to the email address the modal popup will be displayed with a message and if the user try to submit the form without filling the data, it still shows a message of error.

Step 1

initially you need to create a HTML form which can be submitted with details while you are creating a html just give a id such as id="submitform" which will be used in JS code and also define a method to post such as method="post", These all will be defined in form tag these are the attributes of form tag so you can define as following.

<form action="#" class="form-group" autocomplete="off" id="submitform" method="post">

After making the form tag in HTML, you need to make fields which can be used while you are submitting the form. You need to define these field’s id such as id="name" this id is the attribute which is used to provide the id of an element so full syntax to define a input field is following.

<input type="text" name="name" class="form-control" id="name" placeholder="Name" required>

By using this syntax you can define any number of fields in you HTML form so following is the full code of a form which is going to be used to make this example.

Step 2

in 2nd step you need to make make a modal pop which will be displayed while it receive the response to show so following is the code to display bootstrap modal popup.

<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
   <div class="modal-dialog">
     <!-- Modal content-->
     <div class="modal-content">
     <div class="modal-header">
     <h5 class="modal-title" id="quoteModalLabel">Let's Discuss</h5>
      <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
     </div>
     <div class="modal-body">
        <div id="mess"></div>
     </div>
     <div class="modal-footer">
     <button type="button" class="btn btn-primary" data-bs-dismiss="modal">Close</button>
     </div>
     </div>

    </div>
 </div>

as you can see in body section I have define a div with id="mess" which will be used to display the response message so following is the full body code .

<div class="modal-body">
  <div id="mess"></div>
</div>

Step 3

in 3rd step you need to create a js script where you can send form data to php file and after processing the date the modal popup can be displayed with response message. You need to call this script on button click event. In this script you need to use ajax() method to post the form data, You can define type:"POST" and url:"mail.php" in this script after that while receiving success response you need to use $("#myModal").modal("show"); in success function. so following is the full code of JS script.

<script>
    $(document).ready(function(){
    $("#btnsubmit").click(function(){
        
           $.ajaxSetup({
           headers: {
               'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
           }
           });
    
           $('#mess').html('Please Wait...');
           $('#btnsubmit').html('Please Wait...');
           //$("#submitdetails"). attr("disabled", true);
 
              
           $.ajax({
           type:"POST",
           url:"mail.php",
           data: $('#submitform').serialize(),
           success: function(response)
           {
                
               $('#btnsubmit').html('Submit');
               $("#myModal").modal("show");
               $('#mess').html(response);
                
           }
    
           })
       //}
       });
     });
   
 </script>

Form Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,  minimum-scale=1.0, initial-scale=1, shrink-to-fit=no">
    <title>Contact Us</title>
    
    </head>
<body> 

<?php include 'header.php'; ?>
 <section>
        <div class="container">  
            <div class="row g-4">
                <div class="col-lg-8">
                    <h1>&nbsp;</h1>
                <h2 class="">Contact Us</h2>  
                Lorem ipsum dolor sit amet consectetur adipisicing elit. Maiores, incidunt ea itaque aspernatur quam cumque maxime quidem expedita sed commodi delectus, nostrum labore saepe? Similique voluptas maiores repellendus illum earum!
            
                
            </div>
                <div class="col-lg-4">
                    <br/>  
                <h5>Please fill the form,We shall get back to you shortly.</h5>
                <form action="#" class="form-group" autocomplete="off" id="submitform" method="post">
                        
                        <div class="form-group mb-3">
                            <input type="text" name="name" class="form-control" id="name" placeholder="Name" required>
                        </div>
                        <div class="form-group mb-3">
                            <input type="email" name="email" class="form-control" id="email" placeholder="Email" required>
                        </div>
                        <div class="form-group mb-3">
                            <input type="text" name="phone" class="form-control" id="phone" placeholder="Phone Number" required>
                        </div>
                        <div class="form-group mb-3">
                            <input type="text" name="location" class="form-control" id="location" placeholder="Address" required>
                        </div>
                        <div class="form-group mb-3">
                            <textarea name="message" id="message" cols="30" rows="5" class="form-control" placeholder="Message"></textarea>
                        </div>
                        <div class="text-end">
                            <button type="button" class="btn btn-primary" id="btnsubmit">Submit</button>
                            
                        </div>
                    </form>


                        <!-- Modal -->
                        <div id="myModal" class="modal fade" role="dialog">
                        <div class="modal-dialog">

                            <!-- Modal content-->
                            <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="quoteModalLabel">Let's Discuss</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <div id="mess"></div>
                            </div>
                            <div class="modal-footer">
                            <button type="button" class="btn btn-primary" data-bs-dismiss="modal">Close</button>
                            </div>
                            </div>

                        </div>
                        </div>

                </div>
            </div>
        </div>
    </div>

    </section>

<script>
    $(document).ready(function(){
    $("#btnsubmit").click(function(){
       
           $.ajaxSetup({
           headers: {
               'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
           }
           });
   
           $('#mess').html('Please Wait...');
           $('#btnsubmit').html('Please Wait...');
           //$("#submitdetails"). attr("disabled", true);

             
           $.ajax({
           type:"POST",
           url:"mail.php",
           data: $('#submitform').serialize(),
           success: function(response)
           {
               
               $('#btnsubmit').html('Submit');
               $("#myModal").modal("show");
               $('#mess').html(response);
               
           }
   
           })
       //}
       });
     });
  
 </script>
</body>
</html>

In the above code in javascript code when the success function receive the response, the modal popup show the response message using $("#myModal").modal("show"); and $('#mess').html(response);

Mail File – mail.php

<?php

        $name=$_POST['name'];
        $email=$_POST['email'];
        $phone=$_POST['phone'];
        $location=$_POST['location'];
        $message=$_POST['message'];

        if(empty($name) || empty($email) || empty($phone) || empty($location) || empty($message))
        {
            echo "Please fill all the details !";
        }
        else
        {
        $to = "xyz@gmail.com"; // your mail here
        $email = $email;
        $body = "Name : ".$name."\n\nE-mail : ".$email."\n\nPhone : ".$phone."\n\nLocation : ".$location."\n\nMessage : ".$message;
        $subject="Form Details";
        $from="mail@tour.com";
        //mail headers are mandatory for sending email
        $headers = 'From: ' .$from . "\r\n". 
        'Reply-To: ' . $email. "\r\n" . 
        'X-Mailer: PHP/' . phpversion();
      
        if(@mail($to, $subject, $body, $headers)) {
          //$output = json_encode(array('success' => true));
          echo "You have submitted the details successfully !";
          die($output);
        } else {
          $output = json_encode(array('success' => false));
          die($output);
        }
    }

?>

[Download]Responsive Login Page Using HTML, CSS, and JavaScript

LMS / Course Management System Frontend Source Code in HTML,CSS & Javascript

Making WhatsApp Order Form using HTML, CSS, Javascript

Ravindra Kumar

Ravindra is a passionate full stack developer and dedicated blogger with a flair for crafting user-friendly web applications and insightful articles. With expertise spanning front-end and back-end technologies, Ravindra brings ideas to life through innovative coding solutions.

Suggested Reading

How to Create a Simple Login System in PHP

A login system is one of the most essential features of any website or web application. Whether it’s an e-commerce site, a blogging platform, or an internal company portal, user authentication ensures that only authorized users can access specific areas. In this article, we’ll walk through creating a simple login system in PHP using MySQL. […]

Clear Cache After Logout in PHP | Prevent going to back after logout in PHP

One of the most common issues developers face when building a login system in PHP is users being able to press the back button after logging out and still seeing the dashboard or other protected pages. This happens because browsers often cache pages, so even without an active session, the back button shows the previously […]

How to Create a PHP Registration Form with Gmail SMTP Email Confirmation

Building a secure and user-friendly registration system is one of the most common requirements in web development. In this tutorial, we’ll create a registration form in PHP that: Accepts username, email, and password Validates for unique username and email Stores passwords in a secure hashed format Sends a confirmation email using Gmail SMTP with PHPMailer […]

PHP Login Dashboard Template with Bootstrap Free Download

A secure and stylish login dashboard is one of the most essential components of any web application. Whether you’re building an admin panel, school management system, e-commerce backend, or a personal project, having a professional login system with a responsive dashboard can save you both time and effort. In this article, we’ll discuss how you […]

How to send emails by Gmail SMTP Emails in PHP

I’ll show you how to make this Bootstrap form send emails using SMTP. We’ll do this in PHP with PHPMailer, because: It’s reliable Supports SMTP authentication Works with Gmail, Outlook, and custom mail servers Install PHPMailer You can either: Via Composer (recommended) composer require phpmailer/phpmailer Or download from: PHPMailer GitHub and include it manually. HTML […]

How to Create Your Own CAPTCHA (Number Addition) with Form in PHP

CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a simple security mechanism used to prevent automated bots from submitting forms on your website. While there are third-party CAPTCHA services like Google reCAPTCHA, creating a basic number-based CAPTCHA using PHP can be an effective and lightweight solution for small projects. In […]