Контактная форма: почему эта форма не подтверждена? - PullRequest
1 голос
/ 04 марта 2011

У меня есть контактная форма внизу, (одностраничный бизнес / портфолио), веб-сайт.

Сценарий над моим DOCTYPE выглядит следующим образом.

<?php
//If the form is submitted
if(isset($_POST['submit'])) {

    //Check to make sure that the name field is not empty
    if(trim($_POST['contactname']) == '') {
        $hasError = true;
    } else {
        $name = trim($_POST['contactname']);
    }

    //Check to make sure that the subject field is not empty
    if(trim($_POST['subject']) == '') {
        $hasError = true;
    } else {
        $subject = trim($_POST['subject']);
    }

    //Check to make sure sure that a valid email address is submitted
    if(trim($_POST['email']) == '')  {
        $hasError = true;
    } else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$",   trim($_POST['email']))) {
        $hasError = true;
    } else {
        $email = trim($_POST['email']);
    }

    //Check to make sure comments were entered
    if(trim($_POST['comment']) == '') {
        $hasError = true;
    } else {
        if(function_exists('stripslashes')) {
            $comments = stripslashes(trim($_POST['message']));
        } else {
            $comments = trim($_POST['message']);
        }
    }

    //If there is no error, send the email
    if(!isset($hasError)) {
        $emailTo = 'myemail@gmail.com'; //Put your own email address here
        $body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
        $headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

        mail($emailTo, $subject, $body, $headers);
        $emailSent = true;
    }
}
?>

Проверка JQuery работает.

<script type="text/javascript">
$(document).ready(function(){
    $("form").validate();
});
</script>

Контактная форма:

<div class="grid_8">
    <?php if(isset($hasError)) { //If errors are found ?>
        <p class="error">Please check if you've filled all the fields with valid information. Thank you.</p>
    <?php } ?>

    <?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
        <p><strong>Email Successfully Sent!</strong></p>
        <p>Thank you <strong><?php echo $name;?></strong> for using my contact form! Your email was successfully sent and I will be in touch with you soon.</p>
    <?php } ?>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> 
        <div> 
            <label for="name">Your Name:</label> 
            <div> 
                <input type="text" name="contactname" class="required" /> 
            </div> 
        </div> 
        <div> 
            <label for="email">Your Email:</label> 
            <div> 
                <input type="text" name="email" class="required email" /> 
            </div>   
        </div> 
        <div> 
            <label for="subject">Subject:</label> 
            <div> 
                <input type="text" name="subject" class="required" /> 
            </div>
        </div> 
        <div> 
            <label for="comments">Comments:</label> 
            <div> 
                <textarea name="comment" name="comment" class="required"></textarea> 
            </div> 
        </div> 
        <div> 
            <input id="button" type="submit" value="SEND" /> 
        </div> 
    </form>
    </div>

Когда вы отправляете форму, электронное письмо не отправляется, и никакое подтверждение от php. Что я делаю не так?

Ответы [ 2 ]

2 голосов
/ 04 марта 2011

Одна быстрая очевидная проблема, хотя у меня много менее критических. Проще говоря, вы проверяете $_POST['submit'], в вашей форме есть name="submit".

Так измените:

 <input id="button" type="submit" value="SEND" />

Кому:

 <input id="button" type="submit" name="submit" value="SEND" />

Или изменить:

 if(isset($_POST['submit']))

Кому:

 if(count($_POST))
 // OR
 if(!empty($_POST))

Любой из них решит вашу проблему

2 голосов
/ 04 марта 2011

Я не понимаю, почему isset($_POST['submit']) должен возвращать true, если у вас нет поля с name="submit" в вашей форме.

Я предпочитаю использовать массив для всех необходимых данных:

<!-- ... -->
<input type="text" name="mail[contactname]" class="required" /> 
<!-- ... -->
<input type="text" name="mail[email]" class="required email" /> 
<!-- ... -->
<input type="text" name="mail[subject]" class="required" /> 
<!-- ... -->
<textarea name="comment" name="mail[comment]" class="required"></textarea> 
<!-- ... -->

И затем запросить этот массив

if (isset($_POST['mail']))
  // ...
...