Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent bootstrap modal from closing after form submit

I have searched all over the net and did find some solutions but they all used JS or AJAX and helped to an extent only. I am new to PHP and have no clue about AJAX so if someone here could provide me with a solution using PHP & HTML or at most JS.

I have a very simple subscription form inside a bootstrap 3 modal in the footer section of my client's website. The PHP for it verifies that the subscriber is using their official or company email address only to subscribe and some other common/simpler validations.

The form is working great but the issue is that as soon as the person clicks on submit the modal closes and the user doesn't get to see the success or failure message until they reopen the modal from the trigger button. I want the modal to stay open even after the user submits the form and display whether the form submission was a success or not. I hope I was able to explain my issue properly. Here's my HTML & PHP for your reference:

HTML:

  <div id="footer">   
    <div class="container">
      <div class="col-md-6">
        <div id="SubscribeModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">✕</button>
              </div>
              <div class="modal-body">
                <?php include('subscribe.php') ?>
              </div>
              <div class="modal-footer"></div>
            </div><!-- /.modal-content -->
          </div><!-- /.modal-dalog -->
        </div><!-- /.modal -->
        <a data-toggle="modal" href="#SubscribeModal" class="text-muted">Subscribe</a>
      </div>
    </div>
  </div>

PHP:

<?php
    if(isset($_POST['subscribe'])){ 
    /* Configuration */
    $subject = 'Please subscribe me to your Risk Alerts. Thank you.'; // Set email subject    line here
    $mailto  = '[email protected]'; // Email address to send form submission to
    /* END Configuration */
    if(empty($_POST['firstname'])){
        $error = "Please add your first name";
    }elseif(empty($_POST['lastname'])){
        $error = "Please add your last name";
    }elseif(empty($_POST['email'])){
        $error = "Please add your business email";    
    }else{ 
        $firstname      = $_POST['firstname'];
        $lastname       = $_POST['lastname'];
        $email          = $_POST['email'];

        // HTML for email to send submission details
        $body = "
        <br>
        <p>The following information was submitted through the contact form on your website:</p>
        <p><b>Name</b>: $firstname $lastname<br>
        <b>Email</b>: $email<br>
        ";


        $headers = "From: $firstname $lastname <$email> \r\n";
        $headers .= "Reply-To: $email \r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
        $message = "<html><body>$body</body></html>";

        //build list of not allowed providers as lowercase
        $NotAllowedClients = array("aol","applemail","comcast","entourage","gmail","hotmail","outlook");

        preg_match_all('/\@(.*?)\./',$email,$clientarr);            
        $client = strtolower($clientarr[1][0]);            

        if(in_array($client,$NotAllowedClients)){
            //Failed
            $notice = "<div class=\"row-fluid\">
            <div class=\"span12\">
                <h3>Subscription Failed!</h3>
                <p>Please use an official/company email address to subscribe.  <a href=\"?\">Try again</a></p>
            </div>
        </div>"; 
        }else{
            //Passed
            //echo $message;
            mail($mailto, $subject, $message, $headers);
            $notice = "<div class=\"row-fluid\">
            <div class=\"span12\">
                <h3>Subscription successful!</h3>
                <p>Thank you for taking the time to subscribe to our weekly Risk Alerts.</p>
            </div>
        </div>";
        }
    }
} 
?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Risk Alerts</title>
</head>
<body>
<?php
if(isset($notice)){
echo $notice;
}else{
    //Show error for missing field
    if(isset($error)){echo $error;}
?>
    <div class="thumbnail center well well-small text-center">
        <form id="subscription" method="post" action="" class="validate" novalidate>
            <div class="row">
                <div class="col-xs-6 col-md-6">
                    <input type="text" name="firstname" value="" class="form-control input-md" placeholder="your first name"  />
                </div>
                    <div class="col-xs-6 col-md-6">
                <input type="text" name="lastname" value="" class="form-control input-md" placeholder="your last name"  />
                </div>
            </div><p></p>
            <input type="text" value="" name="email" class="form-control" placeholder="your email address" required /><br />
            <div class="clear">
                <input type="submit" value="Subscribe" name="subscribe" class="btn btn-md btn-primary button" />
            </div>
        </form>
    </div> 

    <?php
    }
    ?>
</body>
</html>
like image 599
user3463636 Avatar asked Oct 20 '22 11:10

user3463636


2 Answers

I haven't check your actual PHP but assuming it works, I would submit the form with ajax and process the response.

So, try the following: Add an ID to your modal content:

          <div class="modal-body" id="modal_content">
            <?php include('subscribe.php') ?>
          </div>

Then change your submit button to this :

<a href="javascript:void(0)" class="text-muted" id ="submit_button">Subscribe</a>

Then add this jquery to the bottom of your form page (replace DIRECT_URL_TO_SUBSCRIBE with the correct url):

jQuery(function ($){
    $('#submit_button').click(function(){
        var post_url = 'DIRECT_URL_TO_SUBSCRIBE.php';

        $.ajax({
            type : 'POST',
            url : post_url,
            data: $('#subscription').serialize(), //ID of your form
            dataType : 'html',
            async: true,
            beforeSend:function(){
                //add a loading gif so the broswer can see that something is happening
                $('#modal_content').html('<div class="loading"><img scr="loading.gif"></div>');
            },
            success : function(data){
                $('#modal_content').html(data);
            },
            error : function() {
                $('#modal_content').html('<p class="error">Error in submit</p>');
            }
        });
    })           
});
like image 195
david.philip Avatar answered Oct 23 '22 02:10

david.philip


I was trying to figure out a similar issue so I'll leave this for future googles.

Add to PHP:

    <?php
     $keepOpen="";
     if(isset($notice)){
     $keepOpen="<script> $('#SubscribeModal').modal('show'); </script>";

Add to HTML:

<?php echo $keepOpen; ?>
like image 21
Morgazm12345 Avatar answered Oct 23 '22 03:10

Morgazm12345