Send email using HTML and PHP in separate file

I have this all working (email sends just fine), except that on the HTML page I want the message "Thank you for sending us a message. We will get back to you as soon as possible." to appear on the contact-us.html.   What have I missed?  

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Contact</title>
  <body>

    <header id="header">
        
        </header>


    <section id="contact-page">
        <div class="container">
            <div class="center">        
                <h2>Send A Message</h2>
                <p class="lead"></p>
            </div> 
            <div class="row contact-wrap"> 
                <div class="status alert alert-success" style="display: none"></div><div class="content">
                
                
                  <form  class="contact-form" name="contact-form" action="sendemail.php"   method="post">
                    <div class="col-sm-5 col-sm-offset-1">
                        <div class="form-group">
                            <label>Name *</label>
                            <input type="text" name="name" class="form-control" required="required">
                        </div>
                        <div class="form-group">
                            <label>Email *</label>
                            <input type="text" name="email" class="form-control" required="required">
                        </div>             
                    </div>
                    <div class="col-sm-5">
                        <div class="form-group">
                            <label>Subject *</label>
                            <input type="text" name="subject" class="form-control" required="required">
                        </div>
                        <div class="form-group">
                            <label>Message *</label>
                            <textarea name="message"  required="required" class="form-control" rows="8"></textarea>
                        </div>                        
                        <div class="form-group">
                            <input type="submit"  class="btn btn-primary btn-lg"  >
                        </div>
                    </div>
                </form> 
                  </div><!--/.row-->
        </div><!--/.container-->
    </section><!--/#contact-page-->

</body>
</html>

Open in new window


PHP:
<?php 

$status = array(
		'type'=>'success',
		'message'=>'Thank you for sending us a message. We will get back to you as soon as possible. '
	);
  header('Location: contact-us.html','Content-Type: application/json');
    $name = @trim(stripslashes($_POST['name']));
    $email = @trim(stripslashes($_POST['email']));
    $subject = @trim(stripslashes($_POST['subject']));
    $message = @trim(stripslashes($_POST['message']));

    $email_from = $email;
    $email_to = 'myemail@domain.com';

    $body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;

    $success = @mail($email_to, $subject, $body, 'From: <'.$email.'>');
    echo $status;
  
    die
    ?>

Open in new window

Alison CoxAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
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.

Ray PaseurCommented:
https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html

The PHP script should be modified to produce this message.  Remove the header().  Go down to where it says echo $status (this probably is never executed because of the header() causing a redirection) and put the message you want in an echo statement there.

Also, remove the @ from all of the function calls, so you can find out if any of them are failing and correct the failures.  Remove the die statement.  Remove the ?> close PHP tag.  Avoid that tag whenever you possibly can.

Once you are seeing the message, then you can flesh out a nice looking HTML document with appropriate content and styling.  Most of us who have done this have put the HTML and PHP together into a single script file.  A single script file makes it easier to keep our work organized.
0
Julian HansenCommented:
I would do an AJAX solution
Add this to your html file
<script src="http://code.jquery.com/jquery.js"></script>
<script>
$(function() {
  $('form').submit(function(e) {
    e.preventDefault();
    var form = this; 
    $.post(
      form.action, 
      $(form).serialize(),
      function(resp) {
        if (resp.success) {
          form.innerHTML = resp.message;
        }
      }, 
      'JSON'
    )
  });
});
</script>

Open in new window

PHP
<?php 
$status = array(
  'success'=>false
);
$data = getPost(array('name','email','subject','message'));

if (filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
  $email_to = 'julian@marcorpsa.com';

  $body = <<< BODY
    Name: {$data['name']}
    Email: {$data['email']}
    Subject: {$data['subject']}
    Message: {$data['message']}
BODY;
  $result = mail($email_to, $data['subject'], $body, "From: <{$data['email']}>");

  if ($result) {
      $status['success'] = true;
      $status['message'] = 'Thank you for sending us a message. We will get back to you as soon as possible.';

  }
}
  
die(json_encode($status));

function getPost($fields) {
  $result = array();
  
  foreach($fields as $f) {
    $result[$f] = isset($_POST[$f]) ? $_POST[$f] : '';
  }
  
  return $result;
}
?>

Open in new window


Working sample here
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
Ray PaseurCommented:
Here's my teaching example of a single script file that takes HTML form input and sends the input out via email.
<?php // demo/form_to_email.php
/**
 * Use PHP to Send Email from an HTML Form
 */
error_reporting(E_ALL);


// 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';


// 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']);
    $safe_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;
    $content .= "Idea: $safe_idea" . 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 (NOTE 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

0
Alison CoxAuthor Commented:
Thanks all!  I ended up using the Ajax solution and it was perfect; but I'm going to also play with your last suggestion, Ray, because now I'm finally understanding how it works together and love the results.  Thanks bot
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
HTML

From novice to tech pro — start learning today.