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 = 'xyz#company.com'; // 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. Try again</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>
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 :
Subscribe
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>');
}
});
})
});
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; ?>
Hi this works,
**data-backdrop="static"**
add that to bootstrap modal class. That should solve the issue for you.
<button type="button" data-backdrop="static" data-toggle="modal"
data- target="#yourID">Subscribe</button>
Related
I have a simple PHP question.
I have a textbox where the user enters in their email and submit to be part of our mailing list. Now the textbox is on every page as it's part of our footer. The issue I am getting is that it keeps trying to relocate me to marketing-email.php (where the php that handles all of the form submission occurs'. I want the location to stay on the current page the user is on. I tried the code below with:
header("Location: $_SERVER['HTTP_REFERER']?mailingsent=1");
die;
But it still takes me to marketing-email.php. Plus it gives me a syntax error of unexpected EOF.
How can I get this to work so that after submission, it stays on current page with just a parameter added at the end?
Code below:
footer.php
<?php
$mailingsent=0;
if (isset($_GET['mailingsent'])) {
$_GET['mailingsent'];
}
?>
<html>
<body>
...
<section id="marketing-email">
<form class="marketing-email-form" method="post" action="https://test.com/marketing-email.php">
<div>
<label for="email"><b>Stay updated on any new courses and services we have to offer by joining our mailing list</b></label><br/>
<input type="email" id="market-email" name="market-email" required placeholder="Email"/>
<button type="submit" class="marketing-btn">Send</button>
</div>
</form>
</section>
<?
if (isset($_GET['mailingsent'])) {
echo ' <section id="mailing_list_email_sent" style="background-color:green !important;width:100%;">
<div class="container">
<div class="row">
<div class="col-md-12">
<p class="tagline-content">
Email successfully sent to our mailing list!
<span class="closemailinglistemailmsg"
style="color:white;
font-size:1.5em;
float:right;">×</span>
</p>
</div>
</div>
</div>
</section>';
}
?>
...
<script>
// Get the modal
var modal = document.getElementById("mailing_list_email_sent");
// Get the <span> element that closes the modal
var spanMailingList = document.getElementsByClassName("closemailinglistemailmsg")[0];
// When the user clicks on <span> (x), close the modal
spanMailingList.onclick = function() {
modal.style.display = "none";
}
</script>
marketing-email.php
<?php
$errors = '';
if(
empty($_POST['market-email']
))
{
$errors .= "\n Error: email is required";
}
$email_address = $_POST['market-email'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "\n Error: Invalid email address";
}
if( empty($errors))
{
$email_body = "Request to join mailing list: $email_address";
$email_subject = "Mailing List Metis - $email_address";
mail("test#test.com",$email_subject,$email_body);
header("Location: $_SERVER['HTTP_REFERER']?mailingsent=1");
die;
}
?>
You can just make it as function and include it to the file for submission...
marketing-email.php
Eg: function submitHandleter($data){
And write all of your logic
}
In footer.php
about your form include(marketing-email.php);
And call the function
if(isset($_POST['market-email'])){
submitHandleter($_POST);
}
And keep the form action for the same page
I have put together a simple contact form for my website. Using PHP to POST the data and send directly to my email address. But for some reason every time I visit the page on my website. I still get the test message Displaying under the Form. Then when I reload the website and visit the link again it still displays the thank you message. and automatically sends an email. Im still in testing mode 2 days before my launch and I need this figure out. Considering I am novice to php I dont know what goes where.... check out my website to get a live view https://trillumonopoly.com (click "Contact Us" link in menu) I would like for the contact form to disappear and echo the thank you message once sent. And reset after the page is reloaded. I am also using Jquery ajax to load all my pages into a div container. So I would like to keep the content inside that div without forwarding to the Echo message page, leaving my index page
Heres My ajax code
$(document).ready(function () {
loadMainContent('main');
$('body').delegate('.navMenu', 'click', function (event) {
event.preventDefault();
loadMainContent($(this).attr('href'));
});
});
function loadMainContent(page) {
$('#main').load('pages/' + page + '.php');
}
here is html for the form:
<div class="general row container-fluid"><br>
<center><img src="img/divider.png" class="img-fluid"></center>
<div class="col-lg-6 col-sm-12">
<img src="img/logo.png" class="img-fluid" height="540px" width="540px">
</div>
<div class="col-lg-6 col-sm-12 container"><center>
<br><h1 class="form-title">Contact Us</h1><br></center>
<div class="container">
<form action="pages/mail.php" method="GET" class="box2">
NAME:
<input type="text" name="name" placeholder="YOUR NAME HERE" required>
<br><br>
EMAIL:
<input type="email" name="email" placeholder="YOUR EMAIL HERE" required>
<br><br>
MESSAGE:<br>
<textarea name="message" rows=10 cols=23 placeholder="YOUR MESSAGE HERE" required></textarea>
<br><Br>
<button type="submit" value="Message Sent" class="btn btn-danger btn-lg" style="background-color:"red">SUBMIT</button
</form>
<center><?php include('mail.php'); ?></center>
</div>
</div>
</div>
Here is My simple PHP:
<?php
$name = $POST['name'];
$email = $POST['email'];
$message = $POST['message'];
mail("info#trillumonopoly.com","ILLUMONOPOLY WEB Contact", $message,"From: $email\r\n");
echo "Thank You For Contacting Us!";
?>
Better than check everything before send mail.
if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['message'])){
$name = $POST['name'];
$email = $POST['email'];
$message = $POST['message'];
mail("info#trillumonopoly.com","ILLUMONOPOLY WEB Contact", $message,"From: $email\r\n");
echo "Thank You For Contacting Us!";
}
And send POST request to the index, not mail.php.
<form action="" method="POST">
...
So the user can see your message at the end of contact form.
Were searching for few hours answer on this but I'm completely stacked and brain freezes.
Have subscribe php form with bootstrap modal on successful submission. Everything works, emails passing through, modal showing just after one second or less blank page appear.
I guess that is loaded before form.php file is a separate file but is it there a way to stop loading blank page?
Here is Html code
<form action="form.php" method="post">
<div class="form-group label-floating">
<input name="email" class="control-label form-control text-center" type="text" placeholder="Enter your email address ...">
<button type="submit" class="btn btn-primary" data-toggle="modal" data-target="#myModal">Send</button>
</div>
</form>
<!-- Sart Modal -->
<div class="modal fade" id="myModal" 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" aria-hidden="true">
<i class="material-icons">clear</i>
</button>
<h4 class="modal-title">Thank you</h4>
</div>
<div class="modal-body">
<p>Thank you for registering, we have added you to the waiting list!
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger btn-simple" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- End Modal -->
And here is php code
<?php
$to = "test#test.com";
$from = "no-reply#test.com";
$headers = "From: " . $from . "\r\n";
$subject = "New Beta Subscription";
$body = "New user interested in beta program: " . $_POST['email'];
if( filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) )
{
if (mail($to, $subject, $body, $headers, "-f " . $from))
{
echo "<script type='text/javascript'>
$(document).ready(function(){
$('#myModal').modal('show');
window.stop();
});
</script>";
}
else
{
echo 'There was a problem with your e-mail (' . $_POST['email'] . ')';
}
}
else
{
echo 'There was a problem with your e-mail (' . $_POST['email'] . ')';
}
Also want to change Error messages to show up over modals also, that have it generated just not sure if can call two modals from same index file?
Any help is highly welcome!
Thanks, K>
What you are trying to achieve seems different from what you actually coded.
Let's look at your HTML form. You have attached Bootstrap's data-toggle and data-target attributes on your submit button. This means that when you click that button, it will open the modal AND submit the form. So the user will briefly see a modal and see the page redirect to your PHP file. (This is why you are seeing a modal appear briefly.)
Next, let's look at your PHP file. First of all, when you submit a form from one page to another page, that latter page has no idea of the HTML elements in your former page. This means the code you have inside your echo'd <script> tag actually should not be working as it is looking for an HTML element on your former page.
Now, for your question as to why are you getting a blank page? Well... everything is working fine so your code echo's a <script> tag -- which has no visual indicator. But like I just said, what you have inside the <script> does not work -- so nothing shows up and nothing happens.
So recap of the order of events when you click your button: the modal shows up, the form submits, the form redirects to another page, and that other page echo's nothing.
Below is a poor/quick solution to what I think you are trying to achieve:
Change your HTML file to a PHP file.
Remove data-toggle and data-target attributes off your button, so that it doesn't open the modal right when you click the button
<form action="form.php" method="post">
<div class="form-group label-floating">
<input name="email" class="control-label form-control text-center" type="text" placeholder="Enter your email address ...">
<button type="submit" class="btn btn-primary">Send</button>
</div>
</form>
Move your echo'd script tag from your PHP submission page to your PHP form page and wrap it in a condition as shown below:
<?php if (!empty($_GET['success'])) : ?>
<script>
$(document).ready(function(){
$("#myModal").modal();
});
</script>
<?php endif ?>
Remove your echo'd script tag lines of code in your PHP submission page. Instead, add a code so that it redirects back to your PHP form page. The key part is that you will append a ?success=true at the end of your URL.
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL); // valid email or null|false
if ($email) {
$to = "test#test.com";
$from = "no-reply#test.com";
$headers = "From: " . $from . "\r\n";
$subject = "New Beta Subscription";
$body = "New user interested in beta program: " . $email;
if (mail($to, $subject, $body, $headers, "-f " . $from)) {
header('Location: subscribe.php?success=true'); // replace `subscribe.php` with PHP form page
exit;
}
echo 'There was a problem with your e-mail (' . $email . ')';
} else {
echo 'There was a problem with your e-mail'; // no point in printing $email if it is null
}
Basically, passing ?success=true is for telling the PHP form page that everything went well to open the modal (3).
And that should be it.
A better approach is to learn and use AJAX.
I wrote a simple php script for a form, tested it out, and worked as expected. But when I actually added the script into the original project that I am working on, it suddenly stopped working? I am sure it has nothing to do with the php script as for it worked properly when I tested it; so basically what I am thinking about is that I probably wrote the action attribute wrong? I am pretty sure it is a rookie mistake. Eventually, I am really new to php.
Regards.
HTML code:
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="exampleModalLabel">New message</h4>
</div>
<div class="modal-body">
<form action="contact.html" method="post">
<div class="form-group">
<label name="email" class="control-label">Email:</label>
<input type="text" class="form-control" id="recipient-name">
</div>
<div class="form-group">
<label name="phone" class="control-label">Phone:</label>
<input type="text" class="form-control" id="recipient-mobile">
</div>
<div class="form-group">
<label name="message" class="control-label">Message:</label>
<textarea class="form-control img-responsive" rows="5" id="messageText"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="resetText" class="btn btn-default">Reset</button>
<input type="button" value="Send message" name="send" class="btn btn-danger colorbg"/>
</div>
</div>
</div>
</div>
PHP Code:
<?php
if(isset($_POST['send'])){
$to = 'domain#mail.com';
$subject = 'Solutions';
$mail = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$mailHeader = "From: $mail \r\n Phone: $phone";
$formcontent="Message: $message";
if (!filter_var($mail, FILTER_VALIDATE_EMAIL)) {
echo "<script language='javascript'>
alert('E-mail address is not valid');
var email = document.getElementById('recipient-name');
email.className += ' border-red';
</script>";
} else {
echo "<script language='javascript'>
var email = document.getElementById('recipient-name');
email.className = '';
email.className += ' form-control';
</script>";
if (mail($to , $subject, $formcontent, $mailHeader)) {
echo "<script>
window.setTimeout(function () {
window.location.href = 'test.html';
}, 3000);
</script>";
} else {
echo "<script language='javascript'>alert('There was an error. Please try again.')</script>";
}
}
}
?>
Please note that I uploaded the project on my website in order to actually test the script so the link is something like this: website.com/project/index.html. And I changed the action to action="script/contact.php", action="./script/contact.php, action="contact.php" none worked.
There are two things that makes this not work.
The "submit" button (or any of the other buttons for that matter) is not inside the form-tags. They can be outside, if you assign an ID to the form and assign inputs outside the form, to that form.
There isn't actually a submit-button. You have a regular button. It should be of type="submit", not type="button" (and type="reset" for reset buttons).
In HTML5, you can assign inputs to a form, even outside the actual form-tags. You can do that by assigning an ID to the form (in this example, "myform") and then specifying the form-attribute on your input, like this.
<form id="myform" method="get" action="something.php">
<input type="text" name="name" />
</form>
<input type="submit" form="myform" />
You also, as the other answer already pointed out, the action targets a .html file, which under normal configurations would not parse PHP, but display it as text instead.
I don't see any submit.
Or is that handled by JavaScript somewhere?
Also, the form action= is a html file, if you want the php to work in there, you'll need a .php file.
There is nothing being posted in the html you're showing that is named "send". ( if(isset($_POST['send'])) )
I found the solution here for a similar problem. I hope this is the right place for my answer.
I use buttons A-Z to filter last names in 'listContacts.php'.
Each button triggers a submit. The submit was working from the beginning on
var $char='';
var $characterfilter=function charfilter($char){;
$('#coll').prop('value', $char);
var val2=$('#coll').val();
$('#listcontacts').submit();
};
$('#a').click(function(){
$characterfilter('a');
});
The problem:
<form id='listcontacts' href='' title='use the tabulator to move in the form' style='position: relative; overflow:hidden; height:25em; width:95%' method='post' accept-charset='UTF-8' action='admin.php?listContacts'>
A switch-function in 'admin.php' as below controls the actions:
switch ($action){
case 'login':
login();
break;
case 'logout':
logout();
break;
case 'editService':
editService();
break;
case 'deleteService':
deleteService();
break;
case 'listContacts':
listContacts();
break;
case 'newContact':
newContact();
break;
case 'editContact':
editContact();
break;
case 'deleteContact':
deleteContact();
break;
default:
listServices();
}
When I submitted the form, the Switch in 'admin.php' always returned the default, so I saw the form 'listServices.php' instead after submitting 'listContacts' by using one of the filterbuttons.
The reason for this flaw was: the first call to 'listContacts.php' had been executed by a command:
<a href='admin.php?action=listContacts' >List Contacts</a>
so 'action' had already been set to 'listContacts'
After removing 'action=...' from the formcall as below the form was working.
<form id='listcontacts' href='' title='use the tabulator to move in the form' style='position: relative; overflow:hidden; height:25em; width:95%' method='post' accept-charset='UTF-8'>
It was a little puzzle, took me a few hours and I hope I can help others saving time by posting this.
My website is one pager with nav that links to different parts of the page within the same document. So my contact is at stie.com/#contact rather than site.com/contact.html
I have my contact form coded in html using post method linking to mail.php. Upon hitting the submit button I get redirected to site.com/mail.php where the "Your message was succesfully sent" is displayed. How do I get it so that it displays right on top of the contact form since I don't have a contact.html file to turn into a contact.php and put the php code right where I want the success message to display?
<div class="row">
<div class="12u">
<form method="post" action="mail.php">
<div>
<div class="row half">
<div class="6u">
<input type="text" name="name" id="name" placeholder="Name" />
</div>
<div class="6u">
<input type="email" name="email" id="email" placeholder="Email" />
</div>
</div>
<div class="row half">
<div class="12u">
<input type="text" name="subject" id="subject" placeholder="Subject" />
</div>
</div>
<div class="row half">
<div class="12u">
<textarea name="message" id="message" placeholder="Message"></textarea>
</div>
</div>
<div class="row">
<div class="12u">
Send Message
Clear Form
</div>
</div>
</div>
</form>
</div>
My Mail.php
<?php
//GET INFO FROM CONTACT FORM
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST ['subject'];
$message = $_POST['message'];
$from .= $_POST ['email'];
$to = 'email#site.com';
// compose headers
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
//POST SUBMIT
if ($_POST['sumbit']);
if ($name != '' && $subject != '' && $message !='' && $email != '') {
if (mail ($to, $subject, $from, $message, $headers)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
} else {
echo '<p>Please fill in all required fields!!</p>';
}
?>
You can use URL parameters with PHP:
<?php
$confDisplay = 'display:none;';
// if the url param exists, display confirmation
if(isset($_GET["confirm"]) && $_GET["confirm"]==true){
$confDisplay = 'display:inline;';
}
?>
...
<div style="<?php echo $confDisplay; ?>">
Your form has been submitted!
</div>
...
Just set your form action URL to the same page with ?confirm=true at the end.
Make your action field empty. Put action="" instead of action="mail.php" Then include your mail.php content inside your contact page. As you know, you have to save that page as PHP, too; for example, mycontactform.php. In this way you have more control over the content and format of the "your message submitted" message. If you separate mail.php you can't address divisions in the mycontactform.php.
Security and vulnerability of PHP codes you are using should be addressed after you have completed the page coding and tested it as up and running in your desired format, since it needs more in-depth study of PHP conventions and usages. source: A Set of Step by Step Tutorials Using HTML5, CSS3 and PHP (8)
Note that your script mail.php is vulnerable to headers injection attack. You need to escape your variable $_POST['email']. You have to remove the special characters \n and \r. This can be made easily by using the str_replace function.