This question already has answers here:
Prevent Form resubmission upon hitting back button
(10 answers)
Closed 8 years ago.
I'm developing a php emailer that uses a form which needs to redirect to a "thank you" page that I don't have access to for the purpose of adding code. User input is sent through some simple preg_match functions to make sure it matches the necessary format. If it fails one of these functions, a javascript popup is echoed letting the user know what they need to change. If it makes it through, the data is stored in SESSION variables, and passed to a page where the data is added to the necessary html, and sent as a simple html email. The process.php page then redirects to results.php which clears out the session, and takes the user to the "thank you" page.
My problem is that when the user enters bad data then corrects it and submits, pressing the 'back' button after arriving at the "thank you" page gets me one of these "confirm form resubmit" pages before it goes back to the form. Once it actually gets back to the form after hitting 'back' a second time, the old, bad data is in the form in place of the good stuff. I would like to fix it so the "confirm form resubmit" page never appears, and the user is returned to a blank form if they hit the back button only once. My html:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<table id="form_table" style="280px; border:0px; padding: 0 0 5px 0; border-spacing: 0px;">
<tr>
<td>
<span style="font-size: 12px;">*First name</span>
</td>
</tr>
<tr>
<td>
<input style="padding: 5px; font-size: 12px;" name="firstName" type="text" size="50" value="<?php if(isset($_POST['firstName'])) { echo htmlentities($_POST['firstName']); }?>" />
</td>
</tr>
<tr>
<td style="padding-top: 7px;">
<span style="font-size: 12px;">*Last name</span>
</td>
</tr>
<tr>
<td>
<input style="padding: 5px; font-size: 12px;" name="lastName" type="text" size="50" value="<?php if(isset($_POST['lastName'])) { echo htmlentities($_POST['lastName']); }?>" />
</td>
</tr>
<tr>
<td style="padding-top: 7px;">
<span style="font-size: 12px;">*Email</span>
</td>
</tr>
<tr>
<td>
<input style="padding: 5px; font-size: 12px;" name="emailAddy" type="text" size="50" value="<?php if(isset($_POST['emailAddy'])) { echo htmlentities($_POST['emailAddy']); }?>" />
</td>
</tr>
<tr>
<td style="padding-top: 7px;">
<span style="font-size: 12px;">Phone number</span>
</td>
</tr>
<tr>
<td>
<input style="padding: 5px; font-size: 12px;" name="phoneNumber" type="text" size="50" value="<?php if(isset($_POST['phoneNumber'])) { echo htmlentities($_POST['phoneNumber']); }?>" />
</td>
</tr>
<tr>
<td style="padding-top: 15px;">
<span style="font-size: 12px;">Tell us how we can help</span>
</td>
</tr>
<tr>
<td>
<input style="padding: 5px 5px 15px 5px; font-size: 12px;" name="howHelp" type="text" size="50" value="<?php if(isset($_POST['howHelp'])) { echo htmlentities($_POST['howHelp']); } ?>" />
</td>
</tr>
</table>
<div style="width: inherit;">
<input type="image" id="saveform" src="http://www.fivemm.com/client/tristar/images/consult-btn.jpg" alt="Submit Question!" style="width: 100%; height: 96px; border: none;" />
</div>
<?php echo $msg_to_user ?>
</form>
The processing code, located on the bottom of the same page:
<?php
if(isset($_POST['firstName'])) {
function died($error) {
$error = 'So sorry, but it looks like there are some issues with your form.\\n\\n'.$error;
echo '<script type="text/javascript"> alert("'.$error.'")</script>';
die();
}
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
$string_exp = "/^[A-Za-z .'-]+$/";
$msg_exp = "/^$|^[A-Za-z ?!.'-:]+$/";
if(!preg_match($string_exp,$_POST['firstName'])) {
$error_message .= 'The first name you entered contains invalid characters or is blank.\\n\\n';
}
if(!preg_match($string_exp,$_POST['lastName']) && strlen($_POST['lastName']) > 0) {
$error_message .= 'The last name you entered contains invalid characters.\\n\\n';
}
if(!preg_match($email_exp,$_POST['emailAddy'])) {
$error_message .= 'The email address you entered does not appear to be valid or is blank.\\n\\n';
}
if(strlen($error_message) > 0) {
died($error_message);
}
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$_SESSION['firstName'] = $_POST['firstName']; // required
$_SESSION['lastName'] = $_POST['lastName']; // required
$_SESSION['emailAddy'] = $_POST['emailAddy']; // required
$_SESSION['phoneNumber'] = htmlspecialchars(clean_string($_POST['phoneNumber'])); // required
$_SESSION['howHelp'] = clean_string($_POST['howHelp']);
echo ("<SCRIPT LANGUAGE='JavaScript'>window.location.href='process.php';</SCRIPT>");
}
?>
The process.php page:
<?php
session_start();
if(isset($_SESSION['firstName']) && isset($_SESSION['page1'])) {
$_SESSION['page2']="2";
$first_name = $_SESSION['firstName'];
$last_name = $_SESSION['lastName'];
$email_addy = $_SESSION['emailAddy'];
$phone_number = $_SESSION['phoneNumber'];
$how_help = $_SESSION['howHelp'];
// EDIT THESE 2 LINES BELOW AS REQUIRED
$email_to = 'someguy#domainname.com'; // use for testing
$email_subject = "This Guy Wants To Contact You!"; // Enter intended message here
$email_message = '<html>';
$email_message .= '<head>';
$email_message .= '</head>';
$email_message .= '<body>';
$email_message .= '<h3>You have a new email message!</h3>';
$email_message .= '<table>';
$email_message .= '<tr><td>Name</td><td>'.$first_name.' '.$last_name.'</td></tr>';
$email_message .= '<tr><td>Email Address</td><td>'.$email_addy.'</td></tr>';
$email_message .= '<tr><td>Phone Number</td><td>'.$phone_number.'</td></tr>';
$email_message .= '<tr><td>How can we help?</td><td>'.$how_help.'</td></tr>';
$email_message .= '</table>';
$email_message .= '</body>';
$email_message .= '</html>';
// create email headers
$headers = "From: ".$first_name." \r\n";
$headers .= "Bcc: otherguy#otherdomain.com, otherdude#yetanotherdomain.com\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "\r\n";
// $headers .= 'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
header('Location: results.php');
}
?>
And finally, the results.php page:
<?php
session_start();
if (isset($_SESSION['page2']))
{
session_destroy();
header('Location: http://www.domainname.com/thank-you/');
}
else
{
header('Location: index.php');
}
?>
Short: you can't turn it off.
Long: You should move the processing of form to the beginning.
At first you check if form was submitted and if so you process the data.
On the other hand, when form was not submitted, you just show the form.
The idea here is that when you find errors on processing the data,
you can display the error message and also show the form again.
The good part here is that now you can fill the parts of form that are correct
with the $_POST values you got.
Something like this:
...
<input type="text" name="username" value="<?php echo $_POST["username"]?>" />
...
Now the user just fills the ones that had errors and resubmits.
If it passes you proceed with your email part.
Note that you should sanitize the $_POST array before you use it. ( look: stripslashes, trim, htmlspecialchars )
Hope I made myself clear :)
Sorry, it's late, so I made an example of what i meant:
sample php code
Well, I must admit, the code is a bit strange. As I can see, you have a PHP part in the form page, which test the value from the form. That's it?
I suggest to perform the Rexp in Javascript. Using this you will have a cleaner code: one form with JS for test, submit to process page.
In process page, if you want, you can perform another test, and in case of faillure, fill the session and go back to the form (in that case you will have to read the session).
Maybe the confirm before resubmit came from the fact the page is self-called.
Regards
Peter
Related
I'm creating a small website and I have a one question report form. The problem is the email isn't sending. I'm not sure what I did wrong.
I think there might be something wrong with the php, or maybe the html, I'm not the best with forms. Thanks for the help!
Here's my code:
html
<h2 style="font-size:30px;"><i class="fa fa-exclamation-circle"></i> Report</h2>
</div>
<hr class="descriptionline3">
<div class="modal-body3">
<form action="report.php" id="errorform" onsubmit = "return validate();">
<p style="color:#363636;text-align:left;padding-left:10px;">What seems to be the problem?</p>
<input type="text" class="forminputproblem" id="name" placeholder="Write the problem here..." style="height:20px;font-size:14px;border-radius:6px;display:inline-block;border:1px solid #ccc;padding: 12px 20px;
">
<div style="height:10px;"></div>
<div style="color:red;" id="error_message"></div>
<div style="color:green;" id="success_message"></div>
<div style="height:10px;"></div>
<input name="sumbit" type="submit" value="SEND REPORT">
</form>
php
<?php
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$mailTo = "contact#email.com";
$headers = "Report Form Message";
$txt = "You have received a report form message: ".$name.".\n\n";
mail($mailTo, $txt, $headers);
header("Location: /index.html?reportsent");
}
?>
javascript
function validate(){
var name = document.getElementById("name").value;
var error_message = document.getElementById("error_message");
error_message.style.padding = "10px";
var text;
if(name.length < 10){
text = "✖ Report message has to be at least 10 characters!";
error_message.innerHTML = text;
text = "";
success_message.innerHTML = text;
return false;
}
text = "";
error_message.innerHTML = text;
text = "✔ Report has been submitted! We will get back to you as soon as possible.";
success_message.innerHTML = text;
return true;
}
Thanks!
By checking out the mail function's parameters...
mail($to, $subject, $message, $headers);
It seems like the problem is that your variables are a bit mixed up. Also, "header" doesn't refer to the subject: email headers contain info and have their own syntax. Try this code:
<?php
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$mailTo = "contact#rileysunblockedgames.com";
$subject = "Report Form Message";
$headers = 'From: noreply#rileysunblockedgames.com' . "\r\n" .
'Reply-To: noreply#rileysunblockedgames.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$txt = "You have received a report form message: ".$name.".\n\n";
mail($mailTo, $subject, $txt, $headers);
header("Location: /games.html?reportsent");
}
?>
Also, on your input, you have to define the "name" attribute for it to work properly:
<input type="text" class="forminputproblem" name="name" id="name" placeholder="Write the problem here..." style="height:20px;font-size:14px;border-radius:6px;display:inline-block;border:1px solid #ccc;padding: 12px 20px;">
Also also (and funny enough this is the biggest barrier in your way right now), there is a typo in your submit button's name, so your PHP code will never run:
<input name="submit" type="submit" value="SEND REPORT">
I am writing the code for a simple website where users log in and out and some other basic functions. I would like it to be so when anyone logs in, a logout button is shown on all the pages they visit, and hidden if they are not logged it. I am still new and cannot figure out what is wrong. The logout button appears as soon as i initially click the login button, but when i navigate to other pages the button disappears from my menu.
menu.php
$currentfile = basename($_SERVER['PHP_SELF']);
if($currentfile = basename($_SERVER['PHP_SELF'])){
if (isset($_SESSION['ID'])) {
echo "Home
See Reviews
Write a Review
Search
<a href='logoutconfirmation.php'>Logout</a>
<hr />";
}else{
echo "Home
See Reviews
Write a Review
Search
<hr />";
}
} ?>
index.php
<?php
include "header.inc.php";
$pagetitle= "Login Form";
$showform =1;
$errormsg =0;
$errorusername = $errorpassword = "";
$inputdate = time();
//FIRST CHECK TO SEE IF THE USER IS LOGGED IN
if(isset($_SESSION['ID']))
{
echo "<p class='error'> You are already logged in. </p>";
include_once "footer.inc.php";
exit();
}
if(isset ($_POST['submit'])) {
/*************************************************************
* ALL FIELDS- STORE USER DATA; SANITIZE USER-ENTERED DATA
*************************************************************/
$formfield['username'] = trim($_POST['username']);
$formfield['password'] = trim($_POST['password']);
if (empty($formfield['username'])) {
$errorusername = "The username is required.";
$errormsg = 1;
}
if (empty($formfield['password'])) {
$errorpassword = "The password is required.";
$errormsg = 1;
}
if ($errormsg != 0) {
echo "<p class='error'> THERE ARE ERRORS!</p>";
} else {
//get the user data from the database
try {
$user = "SELECT * FROM Users WHERE username =:username";
$stmt = $pdo->prepare($user);
$stmt->bindValue(':username', $formfield['username']);
$stmt->execute();
$row = $stmt->fetch();
$countuser = $stmt->rowCount();
// if query okay, see if there is a result
if ($countuser < 1) {
echo "<p class='error'> *This user cannot be found in the
database* </p>";
} else {
if (password_verify($formfield['password'], $row['password'])) {
$_SESSION['ID'] = $row['ID'];
$showform = 0;
header("LocationL confirm.php?state=2");
echo "<p> Thank you for logging in! </p>";
} else {
echo "<p class='error'> The username and password
combinations you entered are not correct. Please try again! </p>";
}
}//username exists
} catch (PDOException $e) {
echo 'ERROR fetching users: ' . $e->getMessage();
exit();
}
}
}
if($showform == 1) {
?>
<p class="homemsg">Welcome to the Movie Review Hub! Feel free to look
around or sign in to write your own review.</p>
<form name="login" id="login" method="post" action="index.php">
<table class="center">
<tr>
<th><label for="username">Username: </label></th>
<td><input name="username" id="username" type="text" placeholder="Required Username"
}?><span class="error" <?php if (isset($errorusername)) {
echo $errorusername;
} ?></span></td>
</tr>
<tr>
<th><label for="password">Password: </label></th>
<td><input name="password" id="password" type="password" placeholder="Required Password"
}?><span class="error"> <?php if (isset($errorpassword)) {
echo $errorpassword;
} ?></span></td>
<tr>
<th><label for="submit">Submit: </label></th>
<td><input type="submit" name="submit" id="submit" value="submit"/></td>
</tr>
</table>
<p><a href=index.php>Register.</a></p>
<?php
include_once "footer.inc.php";
}
?>
Like I said i would like the logout button to be show on all of the pages if someone logs in from the index page, the menu is included in all of my files
The logout button initially shows when i press the login button, but when i refresh the page or navigate to another page it goes away.
Like #CBroe mention, try add session_start at start of every page.
Better create config file, put it there and include everywhere.
I think my case is a bit of an oddity... I have a form that is verified by Google Recaptcha. The submit button is disabled until the recaptcha has been interacted with, using a data-callback and some JS. I was just trying out my site on my iOS device using the Safari browser, and I did the Recaptcha verification and a green check appeared, like normal. Then when I scrolled, the container div that the form was in disappeared, and then the entire form was greyed out. It seemed like it went behind the site background.
This is a screenshot of the bug:
So, I am confused to say the least. I have not been able to find any similar issues in the searches I have done. The form is integrated with PHP, here's the code:
<?php
if (isset($_REQUEST['email'])) {
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$recaptcha_secret = "my_secret_key_was_here";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret."&response=".$_POST['g-recaptcha-response']);
$response = json_decode($response, true);
if ($response["success"] === true) {
$to = "someemail#example.com";
$subject = "Contact Form";
$firstname = $_REQUEST['firstname'];
$lastname = $_REQUEST['lastname'];
$email = $_REQUEST['email'];
$comments = $_REQUEST['comments'];
$message = "First Name: \t";
$message .= $firstname;
$message .= "\n";
$message .= "Last Name: \t";
$message .= $lastname;
$message .= "\n";
$message .= "Email: \t";
$message .= $email;
$message .= "\n";
$message .= "Message: \t";
$message .= $comments;
$message .= "\n";
mail($to, $subject, $message, "From:" . $email);
header("Location: sent.html");
} else {
header("Location: failed.html");
}
}
} else {
?>
The else opens up to the page HTML, displaying the page if the conditions are not met. Here's my script:
$(document).ready(function() {
$('#submitbutton').prop( "disabled", true ).attr('title', "Please check the catchpa before submitting the form");
});
var enableBtn = function() {
$('#submitbutton').prop( "disabled", false ).attr('title', "Submit");
}
And here's my form HTML:
<form method="post" action="new.php">
<label for="firstname">First Name:</label>
<input name="firstname" required type="text" />
<label for="lastname">Last Name:</label>
<input name="lastname" required type="text" />
<label for="email">Email Address:</label>
<input name="email" required type="email" />
<label for="comments">Message:</label>
<textarea name="comments" required></textarea>
<div class="center-captcha">
<div class="g-recaptcha" data-sitekey="my_site_key_was_here" data-callback="enableBtn"></div>
</div>
<button class="send-button" id="submitbutton">Submit</button>
</form>
Any help would be greatly appreciated.
Solved it with the answer given on this thread:
Fixed positioning/z-index issue in mobile safari
Apparently my background was being translated to the front of the page, covering up the form inputs and other content.
Adding this line fixed it:
-webkit-transform: translate3d(0,0,0);
I want to make a contact form and my problem is :
by the option select the contact type (peter or Michael) , if i want to contact for example peter and press the submit button it the form goes to his email example peter#gmail.com and so on.... how to solve the problem inside (select option && contact_procees code) please advise me
//// contact.php /////
<form class="contact-form" method="post" name="contact" id="f">
<table width="85%" border="0" cellspacing="0" cellpadding="0">
<td>Contact Person :</td>
**strong text** <td><select id="agents">
<option value="1">Peter</option>
<option value="2">Michael</option>
</select>
</td>
</tr>
<tr>
<td valign="top">Text :</td>
<td><textarea style="background-color:#f5f5f5; color:#000" name="msg" type="text" class="contact-textarea"></textarea></td>
</tr>
</table>
<br />
<br />
<table width="60%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="150px"></td>
<td align="left">
<input type="reset" class="submit" value="Reset" />
<input type="submit" class="submit" value="Send" onclick="sendForm(); return false;" id="btn" />
</td>
</tr>
</table>
</form>
/// JAVA SCRIPT CODE SEND FOR
<script type="text/javascript">
function sendForm() {
document.getElementById('btn').value=".....";
var oData = new FormData(document.forms.namedItem("contact"));
var oReq = new XMLHttpRequest();
oReq.open("POST", "contact_proccess.php", true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
if(oReq.responseText=="1")
alert("Thankyou, the message is sent .");
else
alert("There was error in proccessing your request.Please try again later");
} else {
alert("There was error in proccessing your request.Please try again later");
}
document.getElementById("f").reset();
document.getElementById('btn').value="Send";
};
oReq.send(oData);
}
</script>
//// contact_process.php
<?php
error_reporting(0);
echo "1";
function error(){
exit("0");
}
if(!isset($_POST['name']) or !isset($_POST['work']) or !isset($_POST['subject']) or !isset($_POST['msg'])){
error();
}
$name=$_POST['name'];
$work=$_POST['work'];
$subject=$_POST['subject'];
$msg=$_POST['msg'];
if($name=="" or $work=="" or $subject=="" or $msg==""){
error();
}
$message=
<strong>Name</strong> : '.$_POST['name'].'<br>
<strong>Work</strong> : '.$_POST['work'].'<br>
<strong>contact</strong> : '.$_POST['subject'].'<br>
<strong>Text</strong> : '.$_POST['msg'].'<br>
</div>';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= 'From:Mypage Website <webmaster#mypage.com>' . "\r\n";
$subject="Contact";
$to="peter#gamail.com"; /// what should i do for others
mail($to,$subject,$message,$headers);
?>
You can put your email id in select value like
<select id="agents" name="agents">
<option value="peter#gmail.com">Peter</option>
<option value="michael#gmail.com">Michael</option>
</select>
Get it in php like
$to = $$_POST['agents'];
and then send the email like you are sending
mail($to,$subject,$message,$headers);
I hope answred the question.
I would POST the form to a page called "sendmail.php" and there pick up the selected value (peter/micheal).
You can name them 1 and 2 if you like.
The thing about having it javascript or in the html code is that the mail is in plain sight.
There are robots crawling for mails and the mails printed in html are a likely victim.
Once the send has been done you could echo out thank you and it worked, or did not work.
But my advice is POST the values and send them in php, that way it's secure from crawlers
I have the code
<form name="input" action="messagesave.php" method="POST">
<table style="margin-left: auto; margin-right: auto;">
<tr>
<td style="font-family:'Comic Sans MS', cursive; font-size:20px; text-shadow: 0 0 10px #FFFFFF;">Subject:</td>
</tr>
<tr>
<td><input type="text" value="(Optional)" name="sub" onblur="this.value=!this.value?'(Optional)':this.value;" onfocus="this.select()" onclick="this.value='';"></td>
</tr>
<tr>
<td style="font-family:'Comic Sans MS', cursive; font-size:20px; text-shadow: 0 0 10px #FFFFFF;">Message (Required):</td>
</tr>
<tr>
<td><textarea name="comment" id="comment" cols="60" rows="6"></textarea></td>
</tr>
<tr>
<td>
<?php
require_once('recaptchalib.php');
$publickey = "6LeSzekSAAAAAL32gFlK_vGcqI3-kuoz990KSJHU"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
</td>
</tr>
<tr>
<td><input type="submit" class="submit" value="Submit Message"></td>
</tr>
</table>
</form>
on the main page with the action being
require_once('recaptchalib.php');
$privatekey = "6LeSzekSAAAAAAdAxcsVugyScb8B1D6UoKpjrX2W";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." . "(reCAPTCHA said: " . $resp->error . ")");
}
else {
$comment = $_POST['comment'];
$to = "jsmith#example.com";
$subject = $_POST['sub'];
$message = $comment;
$from = "jsmith#example.net";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
header( 'Location: success.html' ) ;
}
When a user INCORRECTLY enters reCAPTCHA code the page is moved onto a blank page saying recaptcha was not entered correctly.
I want to ask, how can I implement either an javascript alert or red text that appears on the main page so users will not have to press the back button all the time.
Thanks
You have to send the form to the same PHP script itself with a parameter that indicates, that the form has been sent (send in this case):
<form name="input" action="?send" method="POST">
At the beginning of the same PHP script as the form is in check if the form is sent and the entered data is correct:
<?php
$errorArr = array();
if(isset($_GET['send'])) {
// form is sent, do your captcha and other checks here and save the errors in an array
if($captcha->wrong())
$errorArr[] = 'You entered the captcha wrong';
if(count($errorArr) <= 0) {
// No errors occured so do stuff with the correct input of the user
// save it to db for example
}
}
?>
Somewhere on your page you can then print out the error messages like
<?php echo (count($errorArr) > 0)?implode('<br>', $errorArr):null; ?>
Or you can do the whole thing with two different pages and session variables but this is imho to complicate and unnecessary.
If you use Ajax to check your captcha you still need to check it serverside again when the form is sent because someone can disable javascript (as most of the spambot can't interpret javascript) und your captcha veryfication fails.
In your case you end up with something like
<?php
require_once('recaptchalib.php');
$errorArr = array();
$privatekey = "6LeSzekSAAAAAAdAxcsVugyScb8B1D6UoKpjrX2W";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
$errorArr[] = 'The reCAPTCHA wasn\'t entered correctly. Go back and try it again. (reCAPTCHA said: ' . $resp->error . ')';
}
if(count($errorArr) <= 0) {
$comment = $_POST['comment'];
$to = "jsmith#example.com";
$subject = $_POST['sub'];
$message = $comment;
$from = "jsmith#example.net";
$headers = "From:" . $from;
if(mail($to,$subject,$message,$headers) === false)
$errorArr[] = 'Mail could not be sent to us due to a technical error';
// if headers are sent after output already sent you get an error
//echo "Mail Sent.";
header( 'Location: success.html' ) ;
}
?>
<form name="input" action="messagesave.php" method="POST">
<?php echo (count($errorArr) > 0)?implode('<br>', $errorArr):null; ?>
<table style="margin-left: auto; margin-right: auto;">
<tr>
<td style="font-family:'Comic Sans MS', cursive; font-size:20px; text-shadow: 0 0 10px #FFFFFF;">Subject:</td>
</tr>
<tr>
<td><input type="text" value="(Optional)" name="sub" onblur="this.value=!this.value?'(Optional)':this.value;" onfocus="this.select()" onclick="this.value='';"></td>
</tr>
<tr>
<td style="font-family:'Comic Sans MS', cursive; font-size:20px; text-shadow: 0 0 10px #FFFFFF;">Message (Required):</td>
</tr>
<tr>
<td><textarea name="comment" id="comment" cols="60" rows="6"></textarea></td>
</tr>
<tr>
<td>
<?php
require_once('recaptchalib.php');
$publickey = "6LeSzekSAAAAAL32gFlK_vGcqI3-kuoz990KSJHU"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
</td>
</tr>
<tr>
<td><input type="submit" class="submit" value="Submit Message"></td>
</tr>
</table>
</form>
It is going to different page because i guess you are posting the form. What you can do is change your submit button to simple button. Then
$( "#button" ).click(function() {
//your ajax call to validating php
//on success $( "#formId" ).submit();
});
In case you don't want to use javascript just post the form and you can redirect it to the same page from your validation php with a variable set.
header("Location:http://localhost/login.php?x=1")
Check for
if(isset($_GET('x'))){
//your html for error message
}
Perhaps This POST can help
Combine your form and your action handling code into one script that posts to itself with the general form being:
if ($POST['submit'] && $resp->is_valid) {
// Form sent and captcha ok
} else {
// Check, was it submitted already?
if (isset($resp) && !$resp->is_valid) {
echo "<div><p>The reCAPTCHA wasn't entered correctly. Go back and try it again." . "(reCAPTCHA said: " . $resp->error . ")</p></div>";
}
// All the form code here.
}