JQuery выглядит великолепно. Теперь, как мне получить письмо от PHP для отправки? - PullRequest
0 голосов
/ 05 июля 2010

Я использую jQuery для замены изображения здесь после отправки кнопки отправки по электронной почте от.Эта часть работает очень хорошо, однако мне также нужно сгенерировать электронное письмо из содержимого формы.

Вот форма:

            <form action="estimate.php" action="post">
                <fieldset>
                <input type="text" name="name" value="FULL NAME" onfocus="if (this.value=='FULL NAME') this.value='';"/>
                <input type="text" name="phone" value="PHONE NUMBER" onfocus="if (this.value=='PHONE NUMBER') this.value='';"/>
                <input type="text" name="email" value="EMAIL" onfocus="if (this.value=='EMAIL') this.value='';"/>
                <input type="text" name="date" value="MOVE DATE" onfocus="if (this.value=='MOVE DATE') this.value='';"/>
                <input type="text" name="origin" value="ORIGINATING ADDRESS" onfocus="if (this.value=='ORIGINATING ADDRESS') this.value='';"/>
                <input type="text" name="destination" value="DESTINATION ADDRESS" onfocus="if (this.value=='DESTINATION ADDRESS') this.value='';"/>
                <select name="move-type">
                    <option value="" selected="selected">TYPE OF MOVE</option>
                    <option value="Private">Private</option>
                    <option value="Commercial">Commercial</option>
                </select>
                <input id="quoteSubmit" 
                    type="image" src="_images/btn_submit.png" alt="" 
                    onmouseover="javascript:this.src='_images/btn_submit-over.png'" 
                    onmouseout="javascript:this.src='_images/btn_submit.png'"/>
                </fieldset>
            </form>

Вот jQuery:

        // free quote form
    $('#freeQuote form').submit(function(e){

    //Set the data ready for ajax post
    var formdata = $(this).serialize();

    $.post("estimate.php",formdata,function(data){
        if(data.error)
        {
           alert('Error: ' + data.error);
           return;
        }
    });

    //The Image
    var Image = $('<img />').attr({src:'_images/free-quote-confirm.png', width:231, height:267, alt:"Success"});

    //Remove the form
    $('#freeQuote form').remove()

    //Add the image inside the div
    $('#freeQuote').append(Image);

    //Return false so the form does not send as normal. you can also use e.PreventDefault():
    return false;
});

Вот PHP:

<?php # sends contents of  Free Estimate form

if (isset($_POST['submitted'])) {
$errors = array();

// Check for empty fields

if (empty($_POST['name'])) {
    $errors[] = 'Please enter your name.';
} 

if (empty($_POST['email'])) {
    $errors[] = 'Please enter your email address.';
} 

if (empty($_POST['date'])) {
    $errors[] = 'Please enter the date of your move.';
} 

if (empty($_POST['origin'])) {
    $errors[] = 'Please enter the origin of your move.';
} 

if (empty($_POST['destination'])) {
    $errors[] = 'Please enter the destination.';
} 

if (empty($errors)) { // everything is okay

$body = "The following Free Estimate Request has been submitted:\n

    Submitted by: {$_POST['name']}\r
    E-mail: {$_POST['email']}\r
    Phone: {$_POST['phone']}\r
    Move date {$_POST['date']}\r
    Moving from: {$_POST['origin']}\r
    Moving to: {$_POST['destination']}\r
    Move type: {$_POST['move-type']}\r;

    mail ('forrest@rouviere.com', 'Free Estimate Request', $body, 'From: admin@movingsimplified.com');      

    // end email

} else {    
    echo '<h2>Error!</h2>
    <p class="errors">The following error(s) occurred:<br />';
    foreach ($errors as $msg) {
        echo " - $msg<br />\n";
    }
    echo '</p><p>Please go back and try again.</p><p><br /></p>';
}
};

?>

Основная проблема в том, что я могу нажать кнопку отправки без ввода данных в поля, и я не получаю электронное письмо.

Любая помощь будет оценена.

Спасибо.

1 Ответ

2 голосов
/ 05 июля 2010

Если ваш код сниппера не верен, у вас есть следующая проблема ..

$body = " // there is no closing "

Вы также задаете в своем вопросе:

Основная проблема в том, что я могу нажать кнопку «Отправить» без ввода данных в поля, и я не получаю электронное письмо.

Ваш пример предполагает (если нет синтаксических ошибок), что вы не хотите, чтобы электронное письмо отправлялось при наличии ошибок.

Новый исправленный запрос.php

<?php # sends contents of  Free Estimate form

if (isset($_POST['submitted'])) {
    $errors = array();

    // Check for empty fields

    $checkArray = array('name', 'email', 'date', 'origin', 'destination');
    foreach($checkArray as $check) {
        if (empty($_POST[$check])) {
            $errors[] = 'Please enter your '.$check;
        } 
    }

    if (empty($errors)) { // everything is okay

        $body = "The following Free Estimate Request has been submitted:\n

            Submitted by: {$_POST['name']}\r
            E-mail: {$_POST['email']}\r
            Phone: {$_POST['phone']}\r
            Move date {$_POST['date']}\r
            Moving from: {$_POST['origin']}\r
            Moving to: {$_POST['destination']}\r
            Move type: {$_POST['move-type']}\r;

        ";

        mail ($to, 'Free Estimate Request', $body, 'From:  '.$from);      

        // end email

    } else {    
        // If error then NO Email sent
        echo '<h2>Error!</h2>
        <p class="errors">The following error(s) occurred:<br />';
        foreach ($errors as $msg) {
            echo " - $msg<br />\n";
        }
        echo '</p><p>Please go back and try again.</p><p><br /></p>';
    }
};

?>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...