Oliver Martin
Oliver Martin

Reputation: 99

How do I show a Bootstrap modal using PHP?

I don't think my title does this question justice but it may get confusing and I don't want to extend the title over several lines.

Here goes:

I have a single page website which has a contact form with the below code:

<form class="move-down" name="contactform" method="post" action="contact-form-handler.php">
<div class="controls controls-row">
<input id="name" name="name" type="text" class="span3" placeholder="Name"> 
<input id="email" name="email" type="email" class="span3" placeholder="Email address">
</div>
<div class="controls">
<textarea id="message" name="message" class="span6" placeholder="Your Message" rows="7"></textarea>
</div>
<div class="controls pull-right">
<button id="contact-submit" type="submit" class="btn btn-default">Send it!</button>
</div>
</form>

As you can see its action is to call an external php file called "contact-form-handler", which is shown below:

<?php
$errors = '';
$myemail = '[email protected]';//<-----Put Your email address here.
if(empty($_POST['name'])  ||
   empty($_POST['email']) ||
   empty($_POST['message']))
{
    $errors .= die(header('Location: #errorModal'));
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
    $errors .= die(header('Location: #errorModal'));
}

if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email_address\n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' modal
header('Location: #thanksModal');
}
?>

<?php
?>

This has been working fine but as my new site is one page I don't want separate pages loading, nor do I just want to echo black text on a white background.

So my question is - How do I show the Bootstrap Modal window when the submit button is clicked, with php code from inside the external file AND without the page reloading?

I hope it can be done. If it can't can someone help me launch a modal that says error or thanks when the submit button is clicked?

Upvotes: 2

Views: 4525

Answers (1)

pregmatch
pregmatch

Reputation: 2647

yes you can. Since you are not using oop way you can do this

1) on page submit you will assign some $mail_send = true; after email is send

2) you fill then say <?php if ($mail_send) { ?> code for modal here <?php } ?>

3) Drop this header('Location: #thanksModal'); you do not need that.

Put $mail_send = true; instead of that.

that is all.

Upvotes: 2

Related Questions