How to Redirect PHP form with Javascript depending on echo - javascript

I'm looking for a way to redirect after submit depending on the echo
and i used the following code:
<?php
$to = "mymail#gmail.com";
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
$subject = "New Client Call";
$body = 'name: ' .$name."\r\n";
$body = 'email: ' .$email."\r\n";
$body = 'message: ' .$message."\r\n";
$go = mail($to, $subject, $body, "From:<$email>");
if ($go) {
echo "Success";
}
else {
echo "error";
}
?>
<form action="index9.html" method="post" name="redirect" ></form>
<script> document.forms['redirect'].submit()</script>
but i have now two problems:
i am always getting "success" echo. even the client sending empty details.
i want to redirect to an error page with Javascript (if/else) and i don't now how.
BTW i am new in this field so:
I will appreciate your advise/help and be thankful.

You don't need javascript to achive this you can use pure php.
You can use error checking if a field is empty in the form as follows
validate.php
if(isset($_POST['submit'])){
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (isset( $nameErr) || isset($emailErr){
// you have a error
}
else {
$to = "mymail#gmail.com";
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
$subject = "New Client Call";
....
This will check if "email" field is empty if it is it will promp a error "Email is required"
And then in your html you add the error
<form class="form-horizontal" action="validate.php" method="post">
<label for="email">Email: </label>
<input type="text" class="form-control input-sm" name="email">
<span class="error">* <br><?php echo $emailErr;?></span>
<input class="btn btn-info btn-lg" type="submit" name="submit" value="Submit">
</form>
Hope that helps

You seem to be on the right path, before throwing the arguments into the the mailer I would say you can do more sanity checking to make sure all values are entered, this way you avoid trying to send emails that you know will fail, so you fail early and notify the user, you may also see the error message the mail function returns in case of failure to make it easy to rectify any other issues by using the erorr_get_last() method.
echo error_get_last()['message'];
Note: php mail does not verify the headers given, so you have to be 100% sure it's clean and there are no possibilities for the user to inject their own headers, so make sure you sanitize that too.
Then to do redirecting you can just directly replace the echo "success" and echo "error" calls with your javascript part.
So the script would finally look like this:
<?php
$to = "mymail#gmail.com";
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
$subject = "New Client Call";
$missingFieldCount = 0;
if(!isset($_POST['name'])) {
echo "Error: Name requried";
$missingFieldCount++;
}
if(!isset($_POST['email'])) {
echo "Error: Email required";
$missingFieldCount++;
}
if(!isset($_POST['message'])) {
echo "Error: message required";
$missingFieldCount++;
}
if($missingFieldcount > 0) {
echo "Please fill in the missing $missingFieldcount fields, then submit again";
} else {
$body = 'name: ' .$name."\r\n";
$body .= 'email: ' .$email."\r\n"; // Using .= to append instead of replace
$body .= 'message: ' .$message."\r\n";
$headers = "From:<$email>"; //Make sure $email is actually just an email address and not injected headers
$success = mail($to, $subject, $body, $headears);
if ($success) {
$redirectPage = "successPage.html"
} else {
$redirectPage = "errorPage.html"
echo "An error occured:";
//Don't show this to the user, but log it to file instead
//this is here only for demonstration
echo error_get_last()['message'];
}
echo "<form action="$redirectPage" method="post" name="redirect" ></form>";
echo "<script> document.forms['redirect'].submit()</script>";
}
}
?>

Tnq Guys for your answers.
finally i manged a perfect PHP form from all the information i get in this issue. no need Javascript to redirect TO 2 different pages:
1. Thank you page.
2. error page.
and the code is like this:
<?php
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
$to = "mymail#gmail.com";
$subject = " New Client order ";
$errors = 0;
$body ="";
$body .="Name: ";
$body .=$name;
$body .="\n";
$body .="Email: ";
$body .=$email;
$body .="\n";
$body .="Message: ";
$body .=$message;
$body .="\n";
if(isset($_POST['submit'])) { // Checking null values in message.
$name = $_POST["name"]; // Sender Name
$email = $_POST["email"]; // Sender's email ID
$message = $_POST["message"]; // Sender's Message
if (empty($_POST["name"])){
$nameError = "Name is required";
$errors = 1;
}
if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))
{
$emailError = "Email is not valid";
$errors = 1;
}
if (empty($_POST["message"])){
$messageError = "Message is required";
$errors = 1;
}
}
if($errors == 0){
$successMessage = mail($to, $subject, $body, "From: <$email>");
}
else {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.html\">";
}
if ($successMessage){
print "<meta http-equiv=\"refresh\" content=\"0;URL=thanks.html\">";
}
?>

Related

How can I use reCAPTCHA with my form contact?

When I press button Submit on form, reCAPTCHA will allow.
My form can send message without check I'm not a robot.
I don't know if it's about include ajax.
How can I use reCAPTCHA with my form contact?
Thank you very much for your time and assistance in this matter.
This my HTML code.
<form class="callus" onSubmit="return false">
<div id="result"></div>
<input type="text" name="name" id="name">
<input type="email" name="email" id="email">
<textarea name="message" id="message"></textarea>
<div class="g-recaptcha" data-sitekey="XXXXX"></div>
<button id="submit_btn">Submit</button>
</form>
This is my Javascript.
jQuery(document).ready(function($){
$("#submit_btn").click(function() {
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email]').val();
var user_message = $('textarea[name=message]').val();
var post_data, output;
var proceed = true;
if(user_name==""){
proceed = false;
}
if(user_email==""){
proceed = false;
}
if(user_subject==""){
proceed = false;
}
if(user_message==""){
proceed = false;
}
if(proceed) {
post_data = {'userName':user_name, 'userEmail':user_email, 'userMessage':user_message};
$.post('email.php', post_data, function(response){
if(response.type == 'error') {
output = '<div class="alert-danger">'+response.text+'</div>';
}else{
output = '<div class="alert-success">'+response.text+'</div>';
$('.callus input').val('');
$('.callus textarea').val('');
}
$("#result").hide().html(output).slideDown();
}, 'json');
}
});
$(".callus input, .callus textarea").keyup(function() {
$("#result").slideUp();
});
});
email.php
<?php
if($_POST) {
$to_Email = 'demo#localhost.com';
$subject = 'New Contact Inquiry';
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userMessage"])) {
$output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
die($output);
}
$user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
if(strlen($user_Name)<3) {
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
die($output);
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) {
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if(strlen($user_Message)<5) {
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
$message_Body = "<strong>Name: </strong>". $user_Name ."<br>";
$message_Body .= "<strong>Email: </strong>". $user_Email ."<br>";
$message_Body .= "<strong>Message: </strong>". $user_Message ."<br>";
$headers = "From: " . strip_tags($user_Email) . "\r\n";
$headers .= "Reply-To: ". strip_tags($user_Email) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$sentMail = #mail($to_Email, $subject, $message_Body, $headers);
if(!$sentMail) {
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .' Thank you for contacting us.'));
die($output);
}
}
?>
You have to validate captcha code at server side . Once you checked captcha it will give you captcha code.
var captchaCode = this.grecaptcha.getResponse();
Re-Captcaha provide callback functions like
<div class="g-recaptcha" id="headerCaptcha" data-callback="recaptchaCallbackHeader" data-expired-callback="recaptchaExpiryHeader" data-sitekey="xxx"></div>
You have to post this capthca code to backednd for validation inside recaptchaCallbackHeader. (refer below links for detail code)
$secretKey = "Put your secret key here";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
Inresponse of this API you will get .
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo '<h2>You are not a robot #$%K out</h2>';
} else {
echo '<h2>Thanks for posting comment.</h2>';
}
Remember recaptcha provide two types of keys.
Private key which is used on server side for validation of captcha code.
Site-key which is used to render captcha on clint side.
See how reCaptcah works
And Here to validate using PHP.

window.location.reload reloads constantly

I didn't find an answer so im asking you guys.
window.location.reload() constantly reloads without a break.
I'm trying to make something that checks if the form has no input in it, and if doesn't I want it to make an alert, it's working but it reloads constantly. Here's my code:
<?php
$from = $_POST['email_adress'];
$subject = $_POST['subject'];
$select = $_POST['select'];
$message2 = $_POST['message2'];
$name = $_POST['firstname'];
$name2 = $_POST['lastname'];
if ($_POST['firstname'] == "") {
echo '<script language="javascript">';
echo 'alert("First Name is Mandatory.");';
echo 'window.location.reload("contactus.html");';
echo '</script>';
exit;
}
elseif ($_POST['subject'] == "") {
echo '<script language="javascript">';
echo 'alert("Subject is Mandatory.");';
echo 'window.location.reload("contactus.html");';
echo '</script>';
exit;
}
elseif ($_POST['email_adress'] == "") {
echo '<script language="javascript">';
echo 'alert("Email Adress is Mandatory.");';
echo 'window.location.reload("contactus.html");';
echo '</script>';
exit;
}
elseif ($_POST['message2'] == "") {
echo '<script language="javascript">';
echo 'alert("A Message is Mandatory.");';
echo 'window.location.reload("contactus.html");';
exit;
echo '</script>';
exit;
} else {
header("Location: contactus.html");
$email_subject = "A submittion form";
$to ="sudaiguy1#gmail.com";
$headers = "From: sudaiguy1#gmail.com";
$email_body = 'You have been contacted by $name $name2 and his email is $from. \n The message he wanted to say was in the general subject of $select and more specifically $subject and the message is $message2';
mail($to,$email_subject,$email_body, $headers);
}
?>
Maybe this can be an inspiration?
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$is_redirect = isset($_SESSION['to']);
if ($is_redirect && !is_mail_valid($_SESSION)) {
$to = $_SESSION['to'];
$subject = $_SESSION['subject'];
$body = $_SESSION['body'];
}
$_SESSION = array();
} else {
if (is_mail_valid($_POST)) {
$to = $_POST['to'];
$subject = $_POST['subject'];
$body = $_POST['body'];
mail($to, $subject, $body);
} else {
$_SESSION = $_POST;
}
header("Location: index.php");
exit;
}
function is_mail_valid($mail) {
global $errors;
global $valid;
$errors = array();
if (trim($mail['to']) == FALSE) { $errors['empty_to'] = TRUE; }
if (trim($mail['subject']) == FALSE) { $errors['empty_subject'] = TRUE; }
if (trim($mail['body']) == FALSE) { $errors['empty_body'] = TRUE; }
$valid = empty($errors);
return $valid;
}
?>
<?php if (!$valid) { ?>
<script type="text/javascript">
<?php if ($errors['empty_to']) {?>
alert('To: cannot be empty')
<?php } ?>
<?php elseif ($errors['empty_subject']) {?>
alert('Subject: cannot be empty')
<?php } ?>
<?php elseif ($errors['empty_body']) {?>
alert('Body: cannot be empty')
<?php } ?>
</script>
<?php } ?>
<form method="post">
<div>
<label for="to">To</label>
<input id="to" type="email" name="to" value="<?php echo $to;?>" />
</div>
<div>
<label for="subject">Subject</label>
<input id="subject" type="text" name="subject" value="<?php echo $subject;?>" />
</div>
<div>
<label for="body">Body</label>
<textarea id="body" name="body"><?php echo $body;?></textarea>
</div>
<div>
<input type="submit" value="Send">
</div>
</form>
Basically you start using session using session_start()
On POST:
If you don't have an error:
send the mail
redirect to the conctactus page.
If you have an error:
save the input in the session
redirect to the contact us page
On GET:
If you have nothing in session or the mail in session is valid, just render the html.
If you have something in session and that data is invalid, render the html, render the alert script, and set the "value" attributes of the input to maintain the user's input values.
Clear the session data.
This solution requires that you change your contactus.html to contactus.php in order to use sessions.
<?php
// to use a session, you must start it
session_start();
// variable to store any error message
$error = null;
$from = $_POST['email_adress'];
$subject = $_POST['subject'];
$select = $_POST['select'];
$message2 = $_POST['message2'];
$name = $_POST['firstname'];
$name2 = $_POST['lastname'];
if ($_POST['firstname'] == "") {
$error = "First Name is Mandatory.";
} elseif ($_POST['subject'] == "") {
$error = "Subject is Mandatory.";
} elseif ($_POST['email_adress'] == "") {
$error = "Email Adress is Mandatory.";
} elseif ($_POST['message2'] == "") {
$error = "A Message is Mandatory.";
}
if ($error) {
// store the error in a session so that you can use it on another page
$_SESSION['error'] = $error;
} else {
$email_subject = "A submittion form";
$to ="sudaiguy1#gmail.com";
$headers = "From: sudaiguy1#gmail.com";
$email_body = 'You have been contacted by $name $name2 and his email is $from. \n The message he wanted to say was in the general subject of $select and more specifically $subject and the message is $message2';
mail($to,$email_subject,$email_body, $headers);
}
// regardless of whether there is an error or not, it always goes to Contact Us page
header("Location: contactus.php");
exit;
?>
Then in your contactus.php, you would have
<?php
// resume session again
session_start();
?>
<!-- somewhere in your HTML code -->
<?php if (isset($_SESSION['error'])) : ?>
<div class="error-message"><?php echo $_SESSION['error'] ?></div>
<?php endif ?>
<?php
// you probably will want to remove the error afterwards
unset($_SESSION['error']);
?>
If you can't do that, then this solution will not work and you'll have to resort to AJAX (where you send back your error message via the response you get back from your AJAX response).

Redirect sendmail to page instead of error message

I've tried so many variables and been at this for hours and hours for something I know will be so simple haha, but I cannot get this to work... All I need to do, is... when the form is completed I have it redirected to a page instead of the normal error message.
Your help is appreciated.
<?php
//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];
$phone = ($_GET['phone']) ? $_GET['phone'] : $_POST['phone'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$comment = ($_GET['comment']) ?$_GET['comment'] : $_POST['comment'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
//Simple server side validation for POST data, of course, you should validate the email
if (!$name) $errors[count($errors)] = 'Please enter your name.';
if (!$phone) $errors[count($errors)] = 'Please enter your contact number.';
if (!$email) $errors[count($errors)] = 'Please enter your email.';
if (!$comment) $errors[count($errors)] = 'Please enter your comment.';
//if the errors array is empty, send the mail
if (!$errors) {
//recipient - replace your email here
$to = 'me#myemail.com';
//sender - from the form
$from = $name . ' <' . $email . '>';
//subject and the html message
$subject = 'Message from ' . $name;
$message = 'Name: ' . $name . '<br/><br/>
Phone: ' . $phone . '<br/><br/>
Email: ' . $email . '<br/><br/>
Message: ' . nl2br($comment) . '<br/>';
//send the mail
$result = sendmail($to, $subject, $message, $from);
//if POST was used, display the message straight away
if ($_POST) {
if ($result)
echo 'Thank you! We have received your message.';
else
echo 'Sorry, unexpected error. Please try again later';
//else if GET was used, return the boolean value so that
//ajax script can react accordingly
//1 means success, 0 means failed
} else {
echo $result;
}
//if the errors array has values
} else {
//display the errors message
for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
echo 'Back';
exit;
}
//Simple mail function with HTML header
function sendmail($to, $subject, $message, $from) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$result = mail($to,$subject,$message,$headers);
if ($result)
return 1;
else
return 0;
}

I want an alert box after form submit not redirect to thank-you.html

I am wanting say thanks in an alert box instead of redirecting to thank-you.html
Here is my code:
<?php
if (!isset($_POST['submit']))
{
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$contact = $_POST['contact']$message = $_POST['message'];
//Validate first
if (empty($name) || empty($visitor_email))
{
echo "Name and email are mandatory!";
exit;
}
if (IsInjected($visitor_email))
{
echo "Bad email value!";
exit;
}
$email_from = 'tom#amazing-designs.com'; //<== update the email address
$email_subject = "New Form submission";
$email_body = "You have received a new message from the user $name.\n" . "Here is the message:\n $message" .
$to = "tom#amazing-designs.com"; //<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to, $email_subject, $email_body, $headers);
//done. redirect to thank-you page.
header('Location: thank-you.html');
I do not want to redirect page to thank-you.html. I only want to show the alert with "thanks".
Remove header('Location: thank-you.html'); and add javascript
<script>
alert('Thank you!!!');
</script>
Replace header() part with:
printf("<script> alert('Thank You!'); </script>");

a href link in echo not working

function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
I have a php send mail form file.. it includes this code which shows the errors.. I want to add a back button so when they click it, the page goes back to the html form page. when I add this code the php file stops working:
echo "back";
what would the problem be?
this is the full php code file:
<?php
if(isset($_POST['email'])) {
// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "email#here.com";
$email_subject = "Contact Query";
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
echo "back";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['comments'])) {
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$comments = $_POST['comments']; // required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.<br />';
}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
<!-- include your own success html here -->
<body bgcolor="#999">
<center><div style="color:ffffff;">Thank you for contacting us. We will be in touch with you very soon.</div></center>
<body>
<?php
}
?>
replace echo "back"; with echo "<a href='contactus.html'>back</a>";
Change From this
echo "back";
To
echo "<a href='contactus.html'>back</a>";
this would be
echo "back";
or
echo "<a href='contactus.html'>back</a>";

Categories

Resources