Can't get rid of blank php page after submission form - php

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.

Related

PHP/HTML feedback form: How to get the URL of the current page?

I am working on creating a simple feedback form using HTML and PHP. The form and script are working, and I am receiving the submitted emails, except for one issue:
=> I want the feedback form to send the URL of the page where the feedback form was used and receive it in my email. I would like to know which page the user is talking about. For example, if a user clicked the feedback button and opened the feedback form (modal) on http://example.com/features page, I want the URL of that page (http://example.com/features) in my email along with the feedback message.
Here are my HTML and PHP:
HTML Form:
<div id="myModal" class="modal">
<div id="modal-box" class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>Some Heading?</h2>
</div>
<div class="container">
<!--The submitt button in the form redirects action to the PHP script for message submission -->
<form action="http://example.com/mailer.php" role="form" name="feedbackForm" id="feedback_docs" method="post" >
<textarea id="comments" type="text" name="comments" placeholder="Please write your comments about this topic here." style="height:200px"></textarea>
<input id="submit" name="submit" type="submit" value="Send" />
</form>
</div>
</div>
</div>
<div id="myBtn">
<button id="popup" class="feedback-button">FEEDBACK</button>
<p id="demo"></p>
</div>
PHP:
<?php
$comments = $_POST['comments'];
$to = 'feedback#example.com';
$subject = 'Feedback received from website';
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PATH_INFO'];
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
$body = "Message: \r\r $comments";
if ($_POST['submit']) {
if (mail ($to, $subject, $url, $body)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
If you look at the PHP script, I have tried adding the follwing:
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PATH_INFO'];
and I also tried :
$url = "http://".$_SERVER['HTTP_REFERER'].$_SERVER['REQUEST_URI'];,
but neither worked.
I am just learning PHP and scripting, so I have probably made some mistakes. Thank you for your help!
Whichever file the user is in, the request finally goes to the same PHP file. So, you need to find the referrer. But it's unreliable in the PHP side. Instead, what you do is to use hidden inputs and pass that as well:
<input type="hidden" name="fromPage" value="feedbackForm" />
<input type="hidden" name="url" value="https://www.example.com/feedback.html" />
And then capture them in your POST data and send it to your email.
The reason is because you are using some parts incorrectly.
The proper two are
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
Here is the solution to my question. The answer that Forbs provided was very useful.
I changed the $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; to $url = "http://".$_SERVER['HTTP_REFERER'];
The solution was pretty simple, my lack of experience in PHP made it challenging for me!

Form action attribute not working properly

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.

Sending an email using php

Given a standard html form such as the one below;
<form method="post" action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>>
<div class="row half">
<div class="6u"><input type="text" placeholder="Name" name="name" /></div>
<div class="6u"><input type="text" placeholder="Email" name="email" /></div>
</div>
<div class="row half">
<div class="12u"><textarea name="message" placeholder="Message" name="message"></textarea></div>
</div>
<div class="row">
<div class="12u">
<ul class="actions">
<li><input type="submit" class="button" value="Send Message" name="submit" /></li>
<li><input type="reset" class="button alt" value="Clear Form" name="clear"/></li>
</ul>
</div>
</div>
</form>
And the following php
if(isset($_POST['submit'])){
$to = "enquiries#appcloudkent.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$subject = "Website Enquiry";
$message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
if(isValidString($from) && isValidString($name) && isValidString($message)){
mail($to,$subject,$message,$headers);
}
}
It is possible to send an email, however, this approach causes a couple of problems. Because my form is at the bottom of the page, when send is clicked the page is redirected back and the focus goes back to the top of the page.
What is the correct way to provide adequate user feedback to let the user know the email was sent, is it possible to navigate back to the page and automatically scroll to the bottom - allowing me to change the send button to green or something?
Failing that, is there a better approach to doing this?
Thanks
Add an anchor link before your form.
<a id="anchorName"></a>
Post your form to the anchor.
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>#anchorName">
The form action should point to the page itself (like it does in your example) so you can display error messages from validation (like you don't).
If the form is not at the top of your page you can add an anchor:
<h2><a name="theForm">The form</a></h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>#theForm">
If the form is processed properly (=mail sent), it is good practice to redirect to another page, showing a success message. So pressing F5 doesn't submit the form again (and send another mail).
if (mail($to,$subject,$message,$headers)) {
// redirect to page showing success message and exit script
} else {
// redirect to page showing error message and exit script
}
I usually redirect to the same page again, but attach an param ($_SERVER["PHP_SELF"].'?mail_success=1') and then inside the template I decide whether to show the success message, error message or the form:
if (isset($_REQUEST['mail_success'])) {
// show success message
} elseif (isset($_REQUEST['mail_error'])) {
// show error message, technical issues, try again bla bla
} else {
// show the form (including validation errors if necessary)
}
You could submit the form using an XMLHttpRequest, and cancel the default action of pressing submit. jQuery's .post() and event.preventDefault() methods are particularly good at that.

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 = '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>

Debugging PHP email form

I have been trying to set up a simple form on my website that sends an email to my inbox (not the website visitor's) with email address that the visitor enters into the form. It isn't very complicated, but as I am testing, I can't seem to get any email address to work. I don't get any error message either. I will paste the code below.
At the very least, I'd like to know if there could be a problem with the DNS or host configurations. This is my first time building a website, so I'm unsure if the problem is in the code, the HTML (a separate file not pasted here), or the server or host settings.
To make matters more difficult, I have once gotten an error message along the lines of something not configured properly, but I can't seem to get the error message anymore. I don't think I changed any code. That makes me suspect there may be something else going on server-side. Is that feasible?
Thanks in advance for taking a peek.
<?php
$to = "MyEmailInbox#gmail.com";
$from = "mail#example.com";
$headers = "From: " . $from . "\r\n";
$subject = "New subscription";
$body = "New user subscription: " . $_POST['email'];
if( filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) )
{
if (mail($to, $subject, $body, $headers, "-f " . $from))
{
echo 'You will be notified on <b> ' . $_POST['email'] . '</b> :)';
}
else
{
echo 'There was a problem with your e-mail (' . $_POST['email'] . ')';
}
}
else
{
echo 'There was a problem with your e-mail (' . $_POST['email'] . ')';
}
As far as the index.html is concerned, I have a single form next to a Send button. The form presumably takes the user information, filters nonsense out, and then the Send button calls the PHP script. Please find the relevant index.html code below:
<!-- SIGN UP SECTION ############################################### -->
<section id="signup">
<div class="row">
<!-- Title -->
<div class="seven columns centered">
<h2>Sign up to receive our newsletter!</h2>
<!-- Begin the Form -->
<form action="form_sender.php" method="post">
<!-- Input of E-Mail -->
<div class="eight columns">
<input name="email" class="email" type="text" placeholder="YOUR E-MAIL PLEASE ?">
</div>
<!-- Send Button -->
<div class="four columns">
<button name="send" type="submit" class="submit">SEND</button>
</div>
<!-- End of the Form -->
</form>
</div>
<!-- Text Promise we do not spam -->
<div class="twelve columns centered">
<p class="spam">We do not spam.</p>
</div>
</div>
</section>
If you are getting your $_POST variables right, which you can check using "echo", i dont think there is any bug in your code i tried your code without the &_POST vars an it worked fine.
I presume you are using wamp or xampp and testing this on your local system.
Upload the code on webserver and everything will be fine.

Categories