PHP form not providing success Thank You message

I have a form that has everything working except the $success Thank you message.

*** problem 1
The form has a honeypot field that if it is filled out, a different message shows, but
does not send the form. The success message shows correctly on send.php,
but the message is still sent.
** I do not want the message to be sent, I want it to die on the same page contact.html
in the success DIV

*** problem 2
The success message does show up on the send.php page and it sends the message.
** I want the success message to be on the same page contact.html

Is there a way to add the success to show on the same contact.html page in the
success DIV  with the send.php?
or does it need to be done with the js on the send.js page?

I would prefer the php incase bots disable javascript.

All I am trying to achieve is a simple php form that highlights the
required input boxes in red border and use the honeypot to help reduce spam.


Thanks


Here is the code:

contact.html
<!DOCTYPE HTML>
<html>
<head>
<title>Hello</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript" src="send.js"></script>

<style type="text/css">
label{float:left;width:150px;margin:2% 0;}
input,textarea{width:200px;border:1px solid #ccc;font:16px/26px sans;color:#222;margin:2% 0;}
.required{display:none;color:red;}
</style>



</head>
<body>
<p></p>
<!--form-->
<div id="success"></div>
<div id="required"></div>
<form id="myform" name="form" action="send.php" method="post">
<div class="required">* red fields are required</div>
<div><label>Name</label><input id="name" name="name" class="req" type="text" onblur="toUpper(this.value);" /></div>
<div><label>Email</label><input id="email" name="email" type="email" /></div>
<div><label>Phone</label><input id="phone" name="phone" type="tel" class="req" /></div>
<div><label>Confirm</label><input id="confirm_email" name="confirm_email" type="email" class="req2" /></div>
<div><label>Message</label><textarea id="message" name="message" type="text"></textarea></div>
<div><input type="submit" id="submit" /></div>
</form>
</body>
</html>

Open in new window


send.php
<?php
// Clean up the input values
foreach($_POST as $key => $value) {
  if(ini_get('magic_quotes_gpc'))
    $_POST[$key] = stripslashes($_POST[$key]);
 
  $_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}

// Assign the input values to variables for easy reference
$name = $_POST["name"];
$email = $_POST["email"];
$confirm = $_POST["confirm_email"];
$phone = $_POST["phone"];
$message = $_POST["message"];

// Send the email *********** enter your email address and message info *******************
$to = "email@myemail.com"; 
$subject = "Website message: $name";
$message = "From:\n$name\n\nEmail:\n$email\n\nPhone:\n$phone\n\nMessage:\n$message";
$headers = "From: $email";

mail($to, $subject, $message, $headers);


if(!empty($_POST["confirm_email"])) {
    $response = array(
        "success" => true,
        "content" => "<span class='success'><li>Thank you!</li></span>"
    );
    die(json_encode($response));
}
// Die with a success message
$response = array(
    "success" => true,
    "content" => "<span class='success'><li>Thank you! Your message has been sent.</li></span>"
);
die(json_encode($response));

?>

Open in new window


send.js
/*--validation--*/
$(function() {
            function validateform() {
                var valid = true;
                $(".req").css("border","1px solid green");
                $(".req").each(function() {
                    if($(this).val() == "" ||  $(this).val().replace(/\s/g, '').length == 0) {
                        $(this).css("border","1px solid red");$(".required").css("display","block");
                        valid = false;
                    }
                });
                return valid;
                }
            
                $("#submit").click(function() {
                $('#myform').submit(validateform);
                    $('$name').submit();
                });
            
        });

Open in new window

mewebsAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jagadishwor DulalBraces MediaCommented:
You don't have performed any ajax post method to submit your form just using form validation you can not send message from the same page. And see your code which only print the message in the die condition

if(!empty($_POST["confirm_email"])) {
    $response = array(
        "success" => true,
        "content" => "Thank you!"
    );
    die(json_encode($response));
}

Open in new window

0
mewebsAuthor Commented:
do you know the best way to fix it?
0
InsoftserviceCommented:
I would suggest if you are not going my ajax.

remove or comment line no 31 i.e die(json_encode($response));

My solution

if(!empty($_POST["confirm_email"])) {
    $msg ="hank you! Your message has been sent.";
//remove the rest lines
}
$url ="http://yourdesiredlocation&msg=$msg";
header("location:$url");exit;



create an html page and put the below string between body tag

<span class='success'><li><?php echo $_REQUEST['msg'];?></li></span>


This would avoid duplicate post of your value and will display your message and even you would get common message page where you could display your any messages

remove the below line
// Die with a success message
$response = array(
    "success" => true,
    "content" => "<span class='success'><li>Thank you! Your message has been sent.</li></span>"
);
die(json_encode($response));
0
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Ray PaseurCommented:
form has a honeypot field
Usually a honeypot field is not displayed on the form.  
http://www.laprbass.com/RAY_temp_mewebs.html

The idea is that the honeypot would be invisible to a human, but a 'bot would be inclined to fill it in with something.  Another solution is to use a CAPTCHA test.

Form-to-email has kind of "been done" already.  Here is a teaching example that shows the essential moving parts, including the necessary parts to avoid becoming an open relay for spam.

<?php // RAY_form_to_email.php
error_reporting(E_ALL);


// SEND MAIL FROM A FORM


// REQUIRED VALUES ARE PREPOPULATED - CHANGE THESE FOR YOUR WORK
$from = 'NoReply@Your.org';
$subj = 'Contact Form';

// THIS IS AN ARRAY OF RECIPIENTS - CHANGE THESE FOR YOUR WORK
$to[] = 'You@Your.org';
$to[] = 'Her@Your.org';
$to[] = 'Him@Your.org';
$to[] = 'Ray.Paseur@Gmail.com';


// IF THE DATA HAS BEEN POSTED (AT LEAST SOMETHING IN THE EMAIL INPUT CONTROL)
if (!empty($_POST['e']))
{
    // CLEAN UP THE POTENTIALLY BAD AND DANGEROUS DATA
    $safe_mail = clean_string($_POST['e']);
    $safe_name = clean_string($_POST['n']);
    $safe_fone = clean_string($_POST['t']);
    $save_idea = clean_string($_POST['i']);

    // CONSTRUCT THE MESSAGE THROUGH STRING CONCATENATION
    $content    = NULL;
    $content   .= "You have a New Query From $safe_name" . PHP_EOL . PHP_EOL;
    $content   .= "Tel No: $safe_fone" . PHP_EOL;
    $content   .= "Email: $safe_mail" . PHP_EOL;

    // SEND MAIL TO EACH RECIPIENT
    foreach ($to as $recipient)
    {
        if (!mail( $recipient, $subj, $content, "From: $from\r\n"))
        {
            echo PHP_EOL . "<br/>MAIL FAILED FOR $recipient";
        }
        else
        {
            echo PHP_EOL . "<br/>MAIL WORKED FOR $recipient";
        }
    }

    // PRODUCE THE THANK-YOU PAGE
    echo '<p>THANK YOU</p>' . PHP_EOL;
    die('TASK COMPLETE');
}


// A FORM TO TAKE CLIENT INPUT FOR THIS SCRIPT
$form = <<<ENDFORM
<form method="post">
Please enter your contact information
<br/>Email: <input name="e" />
<br/>Phone: <input name="t" />
<br/>Name:  <input name="n" />
<br/>Ideas? <textarea name="i"></textarea>
<br/><input type="submit" />
</form>
ENDFORM;

echo $form;


// A FUNCTION TO CLEAN UP THE DATA - AVOID BECOMING AN OPEN-RELAY FOR SPAM
function clean_string($str)
{
    // IF MAGIC QUOTES IS ON, WE NEED TO REMOVE SLASHES
    $str = stripslashes($str);

    // REMOVE EXCESS WHITESPACE
    $rgx
    = '#'                // REGEX DELIMITER
    . '\s'               // MATCH THE WHITESPACE CHARACTER(S)
    . '\s+'              // MORE THAN ONE CONTIGUOUS INSTANCE OF WHITESPACE
    . '#'                // REGEX DELIMITER
    ;
    $str = preg_replace($rgx, ' ', $str);

    // REMOVE UNWANTED CHARACTERS
    $rgx
    = '#'                // REGEX DELIMITER
    . '['                // START OF A CHARACTER CLASS
    . '^'                // NEGATION - MATCH NONE OF THE CHARACTERS IN THIS CLASS
    . 'A-Z0-9'           // KEEP LETTERS AND NUMBERS
    . '"'                // KEEP DOUBLE QUOTES
    . "'"                // KEEP SINGLE QUOTES
    . '@&+:?_.,/\-'      // KEEP SOME SPECIAL CHARACTERS (ESCAPED HYPHEN)
    . ' '                // KEEP BLANKS
    . ']'                // END OF THE CHARACTER CLASS
    . '#'                // REGEX DELIMITER
    . 'i'                // CASE-INSENSITIVE
    ;
    $str = preg_replace($rgx, NULL, $str);

    // REMOVE EXCESSIVE INPUT
    $str = substr($str, 0, 255);

    return trim($str);
}

Open in new window

And here is an example showing how to highlight the form input controls that do not contain acceptable values.  Maybe you can integrate the principles of these two code samples to come up with a solution that you like.

<?php // RAY_form_highlight_errors.php
error_reporting(E_ALL);


// DEMONSTRATE HOW TO HIGHLIGHT ERRORS IN FORM INPUT
// CLIENT IS ASKED TO PUT IN A VALUE
// IF THE VALUE FAILS OUR TEST WE SHOW AN ERROR MESSAGE
// WE PUT A MARKER NEXT TO THE INPUT CONTROL ON THE FORM
// WE TURN THE FORM BORDER RED
// SEE http://www.w3schools.com/CSS/pr_class_visibility.asp


// THESE CONDITIONS ARE SET FOR THE SCRIPT INITIALIZATION
$error_abc = 'hidden';
$boxer_abc = 'black';
$error_xyz = 'hidden';
$boxer_xyz = 'black';
$error_any = 'hidden';


// CAPTURE AND NORMALIZE THE POST VARIABLES - ADD YOUR OWN SANITY CHECKS HERE
$abc = (isset($_POST["abc"])) ? trim(strtoupper($_POST["abc"])) : NULL;
$xyz = (isset($_POST["xyz"])) ? trim(strtoupper($_POST["xyz"])) : NULL;

// IF ANYTHING WAS POSTED, VALIDATE IT
if (!empty($_POST))
{
    // VALIDATE THE 'abc' FIELD
    if ($abc != 'ABC')
    {
        $error_any = 'visible';
        $error_abc = 'visible';
        $boxer_abc = 'red';

        // BECAUSE THIS FAILED VALIDATION, REMOVE IT FROM THE FORM
        $abc       = NULL;
    }

    // VALIDATE THE 'xyz' FIELD
    if ($xyz != 'XYZ')
    {
        $error_any = 'visible';
        $error_xyz = 'visible';
        $boxer_xyz = 'red';

        // BECAUSE THIS FAILED VALIDATION, REMOVE IT FROM THE FORM
        $xyz       = NULL;
    }

    // DO WE HAVE INPUT FREE FROM ANY ERRORS?
    if ($error_any != 'visible')
    {
        echo "CONGRATULATIONS";
        die();
    }

    // OOPS - WE HAVE ERRORS AND MUST SHOW THE FORM AGAIN
}

// IF NOTHING WAS POSTED, OR IF THERE ARE ERRORS, WE NEED NEW CLIENT INPUT
$form = <<<ENDFORM
<style type="text/css" media="all">
.error_any { visibility:$error_any; }
.error_abc { visibility:$error_abc; }
.error_xyz { visibility:$error_xyz; }
</style>
<pre>
<form method="post">
<span class="error_any">PLEASE CORRECT THE FOLLOWING ERRORS</span>
<span class="error_abc">YOU MUST ENTER 'abc' IN THIS FIELD</span>
PLEASE ENTER "ABC" HERE: <input style="border-color:$boxer_abc;" name="abc" value="$abc" />
<span class="error_xyz">YOU MUST ENTER 'xyz' IN THIS FIELD</span>
PLEASE ENTER "XYZ" HERE: <input style="border-color:$boxer_xyz;" name="xyz" value="$xyz" />
<input type="submit" />
</form>
ENDFORM;

// WRITE THE FORM WITH THE APPROPRIATE CSS STYLES ON THE ERROR MESSAGE FIELDS
echo $form;

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
mewebsAuthor Commented:
@Ray

Thanks

I will look into that. It is confusing at the moment, but I know it has to be good.
You always provide the best.

I hate to ask, but can you look at my existing and help me with that?

I will look at the other, but I do not know if my Brain can take it at the moment.
It's fried.
0
mewebsAuthor Commented:
Oh yeah.

I know, my CSS will hide the honeypot, I was just leaving it showing for now.

thanks
0
mewebsAuthor Commented:
I fixed it to send to a thanks/spam page successfully using the honeypot.

Still trying to get it to echo a message on the same page rather than going to another page.

send.php
<?php
// Clean up the input values
foreach($_POST as $key => $value) {
  if(ini_get('magic_quotes_gpc'))
    $_POST[$key] = stripslashes($_POST[$key]);
 
  $_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}

if(!empty($_POST["confirm_email"])) {
header("location:spam.php");exit;
}

// Assign the input values to variables for easy reference
$name = $_POST["name"];
$email = $_POST["email"];
$confirm = $_POST["confirm_email"];
$phone = $_POST["phone"];
$message = $_POST["message"];

// Send the email *********** enter your email address and message info *******************
$to = "myemail@myemail.com"; 
$subject = "Website message: $name";
$message = "From:\n$name\n\nEmail:\n$email\n\nPhone:\n$phone\n\nMessage:\n$message";
$headers = "From: $email";

mail($to, $subject, $message, $headers);

header("location:thanks.php");exit;

?>

Open in new window

0
mewebsAuthor Commented:
It looks like I am going to have to do this with the Javascript File.
Does not look like I can do it with PHP alone.

Any thoughts on the send.js markup?
0
InsoftserviceCommented:
Is you want to display it on same page just refresh the page with same url and with one more parameter which will be checked if present than to display the message.

I don't think so its needed .just to display the message
0
mewebsAuthor Commented:
@insoftservice

I'm not following you, do you have an example?
0
InsoftserviceCommented:
replace header("location:thanks.php");exit;

with header("location:send.php?msg=THX");exit;

in send.php page

if(isset($_REQUEST['msg']) && $_REQUEST['ms']=='THX' )
{
  echo "Thank you";
}
else
{
 mail($to, $subject, $message, $headers);
}
0
mewebsAuthor Commented:
getting webpage error = Redirect loop

This is the code

send.php
<?php
// Clean up the input values
foreach($_POST as $key => $value) {
  if(ini_get('magic_quotes_gpc'))
    $_POST[$key] = stripslashes($_POST[$key]);
 
  $_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}

// Honeypot don't send
if(!empty($_POST["confirm_email"])) {
header("location:spam.php");exit;
}

// Assign the input values to variables for easy reference
$name = $_POST["name"];
$email = $_POST["email"];
$confirm = $_POST["confirm_email"];
$phone = $_POST["phone"];
$message = $_POST["message"];

// Send the email *********** enter your email address and message info *******************
$to = "myemail@myemail.com"; 
$subject = "Website message: $name";
$message = "From:\n$name\n\nEmail:\n$email\n\nPhone:\n$phone\n\nMessage:\n$message";
$headers = "From: $email";

mail($to, $subject, $message, $headers);

header("location:send.php?msg=THX");exit;

if(isset($_REQUEST['msg']) && $_REQUEST['ms']=='THX' )
{
  echo "Thank you";
}
else
{
 mail($to, $subject, $message, $headers);
}


?>

Open in new window

0
RobOwner (Aidellio)Commented:
I've requested that this question be deleted for the following reason:

The question has either no comments or not enough useful information to be called an "answer".
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Web Languages and Standards

From novice to tech pro — start learning today.