using modal popup for php redirect - php

I have a php mail form (working fine) that currently redirects to a thank you page. I am revamping the site and would like to (instead of redirecting to another page) have (upon successful submit) a modal popup appear and say thank you. I would also need to have the form cleared since the user would be staying on the current page. I have searched (both on stackoverflow and web searches) for a solution. I have found a few "ideas" but nothing that has worked. I am currently using modal popups on other things on the site (since revamp) and generally understand how they work. I also have a basic understanding of php. I was thinking if its possible(?) to have some type of javascript in header to invoke the modal popup. I've also seen ideas of it needing to be AJAX.
Any help would be greatly appreciated.
Here's my html for form:
<p class="formrequired">Required fields are marked with an asterisk(*)</p>
<form action="form.php" method="post">
<ol class="forms">
<li><label for="first_name">*First Name</label><input type="text" name="first_name"/></li>
<li><label for="last_name">Last Name</label><input type="text" name="last_name"/></li>
<li><label for="email">*Email</label><input type="text" name="email"/></li>
<li><label for="comment">*Message</label><textarea name="comment"cols="45" rows="5"></textarea></li>
<li><input type="submit" value="Submit" class="submit"/>
</ol>
</form>
and my php:
<?php
$myemail = "person#email.com";
$first_name = check_input($_POST['first_name'], "Please enter your first name");
$last_name = check_input($_POST['last_name']);
$email = check_input($_POST['email']);
$comment = check_input($_POST['comment'], "Please enter your message");
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("E-mail address is not a valid email address");
}
$subject="New form submitted on Napoleonville Fire";
$message = "Hello Jordy!
Your contact form has been submitted by:
First Name: $first_name
Last Name: $last_name
E-mail: $email
They left the following message:
$comment
End of message.
";
mail($myemail, $subject, $message);
header('Location: thankyou.html');
exit();
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<b>Please correct the following error:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php
exit();
}
?>
Again, thanks for any and all help.
I will have a "part 2" if this can be solved.

Two flows I can think of
Non-AJAX
Submit your form to the server as you currently do. Then when redering the success page, render the page with the modal showing. Provide a close button of some sort that set's display none on it or deletes it from the DOM altogether. In this approach you can handle rendering the empty form with PHP. This is the more traditional paradigm.
AJAX
For this, add an event handler to the form submission. Submit the form via AJAX, but don't immediately clear the form fields. Wait for the response from the server. If the server finds a validation error in the form submission for example you will have to update the form to reflect this error. If the server returns a success response, clear the form fields with Javascript and show the modal.

Related

How to make multiple AJAX queries after user input?

This seems like such a simple thing, but I have not been able to find adequate guidance on it for the life of me. I have only been able to find things about successive AJAX queries regardless of user input, like this or this.
What I'm trying to do is create a survey such that after a user answers a question, the website replaces the question with the next question, and so on.
Here's what I have so far (in a .php file):
In <head>, I have a function for each successive element to call:
<script type="text/javascript">
function nextPage(url) {
$("#consent-form").empty();
$("#consent-form").load(url);
}
</script>
Maybe that's just not how it's done. I have no idea. Like I said, I have not been able to find adequate help on this. As far as I can tell, empty() should not delete #consent-form, but only its content and children, which is exactly the behavior I want.
This is the initial html and php for the div I want to swap out after each answered question:
<div id="consent-form">
<?php
// Check for a valid email address.
$email = $emailErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$emailErr = "* Your email address is required.";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "* Please enter a valid email address.";
} else {
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$query = "INSERT INTO survey VALUES ('" . $email . "','" . $actual_link . "','','')";
mysql_query($query);
echo '<script type="text/javascript">'
, 'nextPage("survey.php");'
, '</script>'
;
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<p>
[Consent form text]
</p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Please enter your email address: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error"> <?php echo $emailErr;?></span>
<br>
<input type="submit" value="Begin Study">
</form>
</div>
As I'm sure you can tell, I'm trying to do some form validation there.
This succcessfully injects the content of the next page ("survey.php") into the consent-form div. "survey.php" includes the following, using the nextPage() function shown above:
$("#csp_form").on('submit', function() {
nextPage("other.php");
});
But this fails to inject the consent-form div with "other.php".
Now, however, not even the form validation works. According to Firebug, the jquery library has raised some sort of error, even when I comment out all the jquery and javascript functions, and it's stuck in some perpetual loading operation. (This issue has been fixed.)
I am about to start throwing things. I have tried many different other techniques, but none of them worked and I have lost track of them. Hopefully this latest version will be sufficient to get guidance on this.
Sorry all that was so long, but usually people complain that there's too little information, so I wanted to make sure to include everything.
EDIT:
Per request, here's the current full content of survey.php (with the text content changed for privacy purposes):
<script type="text/javascript">
$("#icecream_form").on('submit', function() {
nextPage("other.php");
return false;
});
</script>
<br>
<h2>What's your favorite ice cream flavor?</h2>
<form method="post" id="icecream_form">
<input type="radio" name="icecream" value="vanilla"> Vanilla
<br>
<input type="radio" name="icecream" value="chocolate"> Chocolate
<br>
<input type="radio" name="icecream" value="other"> Something else
<br>
<input type="radio" name="icecream" value="none" checked> I don't have a favorite.
<br>
<br>
<input type="submit" name="icecream_submit" value="Go" onsubmit="return(false)">
</form>
After hitting submit, the content from consent-form comes back with an error message from the email form ("Please enter an email address"), implying that the email form was posted again. I cannot comprehend how that is possible if all the stuff from that div had truly been replaced by the stuff in survey.php.
I believe the issue was just that I was missing $(document).ready(function () { before $("#icecream_form").on('submit', function() {. This enabled return false; to actually work.
However, I also swapped out the PHP form validation with a jQuery version and deleted the nextPage() function in lieu of just having each page have their own .load(), so those things may also have made a difference.

PHP: Refresh page on invalid form submit

How can I refresh a page with a form on submission pending the outcome of the submitted data and display a result.
e.g I have a page with a form:
<form action="" method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
The engine that handles the form is external, but required in the page:
require_once 'form_engine.php';
form_engine.php checks the input,
$success = "true";
$errorMessage = " ";
$name = $_POST['name'];
if ( $name == '') {
$errorMessage = 'Please enter your name';
$success = false;
}
else (if $success = true) {
// do something with the data
}
The form page contains the result:
<form action="" method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
<p><?php echo $errorMessage; ?></p>
Will the error message get displayed after the form is submitted incorrectly? Or do I have to use a session to store it?
You need something like this:
if (!isset($_POST['name']))
instead of
if ( $name == 'name')
UPDATE
Try this, it should give you the idea:
<?php
$errorMessage = false;
if (isset($_POST['submit'])) {
if (!isset($_POST['name']) || $_POST['name']=='') {
$errorMessage = 'Please enter your name';
}
else {
// do something with the data
echo "Success!!";
}
}
?>
<form method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="submit" name="submit" />
</form>
<p><?php if ($errorMessage) echo $errorMessage; ?></p>
Note: leaving out the action attribute will just submit the form to the current page
Note 2: The PHP here could very well be stored in another page. Using require() is the same as putting the code directly into the page.
You can use redirect on php side:
header('Location: www.mysite.com/index.php');
You seem to be a little confused in terms of the exact process that occurs in terms of rendering a page, as do some of those commenting. You do not need to use sessions to solve this problem. There is no need to store anything server-side between page requests because the user's browser with retain everything that you need, at least for this situation. My guess is the others took you mentioning an "external engine" and thought that the form would be submitting away to a different site/page.
form loops
Below is a diagram showing a typical form request loop:
You do not have to do this, as coding is as much about personal preference to anything else, but typically people will design their form to submit back to the same URI that generated it — as you seem to be doing in your example, by leaving the action attribute blank. By doing this, as long as you embed everything you wish to pass back to the server side within the form — each time the user submits — that information will be resent and be available in PHP.
Obviously you need to be wary of what information might constitute as sensitive, as this data should only ever be written into markup if your requests are protected by HTTPS/SSL. You should also filter/escape any user input to prevent markup injection into your site. You can prevent many problems by using htmlentities, however this can cause issues depending on the values you are trying to capture from the user. Because you are using double quoted HTML attributes (the right way to do them ;) I have not set the ENT_QUOTES option.
back to the point
So in the above loop the user will be shown the form for the first time, and after any subsequent submit, which means that each time your PHP notices that there is an error you can just add your message into the page flow. The trick with this kind of system is what exactly do you do once the form is fully complete. To get out of the loop most people will use a header location call:
<?php
require_once 'form_engine.php';
$name = !empty($_POST['name']) ? trim($_POST['name']) : '';
$name = htmlentities($name);
if ( $success ) {
header('location: next-step.php');
exit;
}
?>
<form action="" method="post">
<input type="name" value="<?php echo $name; ?>" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
<?php
if ( $errorMessage ) {
echo "<p>$errorMessage</p>";
}
?>
form engine repairs
You should also rectify your form_engine.php as per my comments above and Shekhar Joshi's answer, although I would keep the header code outside of your engine logic, and leave that decision to the code that requires in the engine — as the above does.
may be, you are looking for this! the header() method.
$success = true;
$errorMessage = " ";
$name = $_POST['name'];
if(isset($_POST['name'])) {
if ( $_POST['name'] == '') {
$errorMessage = 'Please enter your name';
$success = false;
header('Location: www.something.com/some.php');
}
else if ($success == true) {
// do something with the data
}
}

how do I get the message after submit to appear inside the pop up instead of on a different page

I have a contact form that I'm using Jquery .load to import a php file into any of the pages the nav will be on. Example below.
http://madaxedesign.co.uk/dev/index.html
I'm aware that the action form needs to be changed so it is connected to the right place. But how would I do that if it is on different pages and imported into a page. Because at the moment it is set to contact.php but after it is submitted it goes to that page and doesn't import the message into the pop up. So really I need it to be the file name depending on what page it is on.
So I suppose the question is how do I get the message after submit to appear inside the pop up instead of on a different page?
Code:
<?php
$your_email = "maxlynn#madaxedesign.co.uk";
$subject = "Email From Madaxe";
$empty_fields_message = "<p>Please go back and complete all the fields in the form.</p>";
$thankyou_message = "<p>Thank you. Your message has been sent. We Will reply as soon as possible.</p>";
$name = stripslashes($_POST['txtName']);
$email = stripslashes($_POST['txtEmail']);
$message = stripslashes($_POST['txtMessage']);
if (!isset($_POST['txtName'])) {
?>
<form method="post" action="contact.php">
<div id="NameEmail">
<div>
<label for="txtName">Name*</label>
<input type="text" title="Enter your name" name="txtName" />
</div>
<div>
<label for="txtEmail">Email*</label>
<input type="text" title="Enter your email address" name="txtEmail" />
</div>
</div>
<div id="MessageSubmit">
<div>
<textarea maxlength="1200" title="Enter your message" name="txtMessage"></textarea>
<label for="txtMessage">Message</label>
</div>
<div>
<input type="submit" value="Submit" /></label>
</div>
</div>
</form>
<?php
}
elseif (empty($name) || empty($email) || empty($message)) {
echo $empty_fields_message;
}
else {
$referer = $_SERVER['HTTP_REFERER'];
$this_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"];
if ($referer != $this_url) {
echo "You do not have permission to use this script from another URL, nice hacking attempt ;p.";
exit;
}
mail($your_email, $subject, $message, "From: $name <$email>");
echo $thankyou_message;
}
?>
You should use ajax, send the email without refreshing page.
What you want to do is only possible in javascript, this is a language that gets executed by the browser. Javascript self is a nasty language but there are many extensions/plugins to make this very easy like jQuery. i suggest you to learn this language, you will find a new world opening in web development ;-). eg: http://learn.jquery.com/
give your form an id:
<form method="post" id="test-form" action="contact.php">
so you can reference to it with jquery
now you can catch the form submit action with jQuery:
$('#test-form').submit(function() {
//send your data to your server and get the html data
$.post('contact.php', $(this).serialize(), function (data){
//here you can add the (html)data returned by the action to your page.
$('body').append(data); //append data to body of html page
})
return false; //stop form from going to the next page
});
this code is based on a javascript plugin: jQuery, if you want to do anything dynamic on your page without reloading the page, you need to use javascript.

Wordpress contact form

I've a very basic contact form on my Wordpress site (hard coded) and I can't get things to work. It works locally fine through XAMPP and I'm sure it's something I'm just missing but any help would be greatly appreciated. Thanks in advance!. I'm also using a template I created
<?php /* Template Name: contact */?>
<?php get_header(); ?>
<?php
//vars declared to store form input
$name=$email=$comment=$phone="";
//Error vars - to relay error message to the form
$nameError=$emailError=$commentError="";
$error_message="";
$sentMessage="";
$status=0; //Will monitor if all fields have no errors and increment if so.
function sanitise_var($string){
htmlentities($string);
strip_tags($string);
return stripslashes($string);
}
if(isset($_POST['submitted'])){
if($_POST['name']==""){
$nameError="Please enter a name";
$error_message="Oops, error in the form. Please check";
}
else {
$name=$_POST['name'];
++$status;
}
if($_POST['email'] == "" || !preg_match("/^[a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", $_POST['email'])){
$error_message="Oops, error in the form. Please check";
$emailError="Please enter a valid email";
}
else{
$email=$_POST['email'];
++$status;
}
if(!$_POST['phone']=="") $phone=$_POST['phone'];
if($_POST['comment']==""){
$error_message="Oops, error in the form. Please check";
$commentError="Please enter a message";
}
else{
$comment=$_POST['comment'];
++$status;
}
}//submitted if statement
if($status==3 && $_POST['submitted']){
$sentMessage="From: $name, email: $email, Phone: $phone, Comment: $comment";
wp_mail("mathornley#gmail.com", "From Android Scoop contact form", $sentMessage);
echo "Thanks, your email was sent successfully!";
}
else{
echo<<<SOQ
<div class="entry-content">
<h1 class="entry-title">Contact</h1>
<p class="contact">
If you have a query drop us a line using the form below. We're always happy to hear from people with ideas for posts and content they'd like to feature or maybe write about. Or maybe you just have some feedback you'd like to share with us. Why not just swing by and say hello.
</p>
<p class="requiring">* Denotes required fields</p>
<div class="form_left">
<form action="/contact/" method="POST">
<p><label>Name:</label><input type="text" name="name" value="$name"/></p>
<p class="error">$nameError</p>
<p><label>Email</label><input type="text" name="email" value="$email"/></p>
<p class="error">$emailError</p>
<p><label>Phone:</label><input type="text" name="phone" value="$phone"/></p>
<input type="hidden" name="submitted" value="yes"/>
<input type="submit" value="Send your message"/>
</div>
<div class="form_right">
<p><label>Message:</label><br/><textarea name="comment" rows="20" cols="20">$comment</textarea></p>
<p class="error">$commentError</p>
</form>
</div>
</div>
SOQ;
}
?>
<?php get_footer();?>
Try to use blank value for action like:
<form action="" method="POST">
If that doesn't work try renaming name parameter of the first input field to something else like:
<input type="text" name="myname" value="$name"/>
Am not aware about the wordpress but as the general PHP rules go, and according to what you replied me in the comment, the error lies here
<form action="/contact/" method="POST">
----^----
Why won't you use some out-of-the-box contact form for WordPress? For example, Contact Form 7 is pretty good.
Contact Form 7 is an open source software and can manage multiple contact forms, plus you can customize the form and the mail contents flexibly with simple markup. The form supports Ajax-powered submitting, CAPTCHA, Akismet spam filtering and so on.
Installation
Upload the entire contact-form-7 folder to the /wp-content/plugins/
directory.
Activate the plugin through the ‘Plugins’ menu in
WordPress.
You will find ‘Contact’ menu in your WordPress admin
panel.
Create a contact form, copy it's url, paste it everywhere you want.
Contact form will appear exactly in it's location.
If you want an example, you can check out this site to see it's look & feel.

PHP Contact Form - Want to stay on my site after send

I am in the process of creating a PHP contact form and all I have is that little problem, with the php script I have, that when the email was send out a new "Thank you" page is called.So the actual site with the contact form disappears BUT I DON`T WANT THAT HAPPEN.If the send button is hit I want to stay on my site, showing an empty contact form and maybe below the contact form just 1 line, saying "Thank you.....".How can I make that happen? Is there any code snippet out there that can explain to me what I have to include to my html and to my php file? Hopefully it will...Below is how my php ends right now.
// send Email
if (#mail( $empfaenger, htmlspecialchars( $betreff ), $mailbody, $mailheader ))
{
// if email was successfully send
echo 'Thank you for your Email. We will get in touch with you very soon.';
}
EDIT
#FreekOne
Currently I am using your code with a slight modification because I wanted to make the thank you and or error panel make slide out and have the text fade in. The script is accepting my code (because it is still working) but actually I can not see that the text actually fades in. I have seen samples of sliding panels with fading in text. So it seems to be a wrong kind of coding that I did.Please view the code here if you want: http://jsbin.com/ohuya3Maybe you can point me to the right direction. Of course, help would be appreciated from all of you guys here around.
Set the form to send the data to the same page, and have your script listen for a submit. Something like:
contact.php
<?php
// Check if form was previously submitted
if(isset($_POST['myFormSubmitted'])) {
// Do your form processing here and set the response
$response = 'Thank you for your Email. We will get in touch with you very soon.';
}
?>
<!-- HTML here -->
<?php
if (isset($response)) { // If a response was set, print it out
echo $response;
}
?>
<form method="POST" action="contact.php">
<!-- Your inputs go here -->
<input type="submit" name="myFormSubmitted" value="Submit">
</form>
<!-- More HTML here -->
UPDATE
Considering the provided extra info, I would personally do it with jQuery, through AJAX. First, setup your form and the container for the result:
HTML
<form id="myForm" method="POST" action="contact.php">
<input type="text" id="name" name="name">
<input type="text" id="email" name="email">
<input type="text" id="message" name="message">
<input type="submit" name="myFormSubmitted" value="Submit">
</form>
<div id="formResponse" style="display: none;"></div>
Then setup the php script which handles the submitted data and outputs the response.
PHP (contact.php)
<?php
if(isset($_POST['myFormSubmitted'])) {
// Do your form processing here and set the response
echo 'Thank you for your Email. We will get in touch with you very soon.';
}
?>
And finally, the jQuery script which will submit your form without leaving the page and insert the result in your result container (with a nice and simple fade in effect).
jQuery
$("#myForm").submit(function() {
$.post('contact.php', {name: $('#name').val(), email: $('#email').val(), message: $('#message').val(), myFormSubmitted: 'yes'}, function(data) {
$("#formResponse").html(data).fadeIn('100');
$('#name, #email, #message').val(''); /* Clear the inputs */
}, 'text');
return false;
});
Hope this helps !
All these answers below are wrong. It will make you occasionally spammed with doubled messages and confuse customers.
Though the solution is kinda tricky
First of all you have to learn the Golden rule:
After processing POST request, your code should redirect a browser using GET method. No exceptions.
Thus, first make it like this
if ($_SERVER['REQUEST METHOD']=='POST') {
mail( $empfaenger, htmlspecialchars( $betreff ), $mailbody, $mailheader );
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
// your form goes here
You ought to do it anyway.
Next, if you still want to show this useless message, you have several ways to do it.
using GET parameter
using cookie
ising AJAX.
for example, to use a GET parameter
if ($_SERVER['REQUEST_METHOD']=='POST') {
mail( $empfaenger, htmlspecialchars( $betreff ), $mailbody, $mailheader );
header("Location: ".$_SERVER['PHP_SELF']."?thanks");
exit;
}
if ($_SERVER['QUERY_STRING']=='thanks') {
echo 'Thank you for your Email. We will get in touch with you very soon.';
}
// your form goes here

Categories