为什么我的表单会出错?

时间:2015-10-25 19:38:45

标签: php ajax forms validation

我一直在使用这个PHP代码作为我的表单验证的一部分。它在过去的6个月里一直很好用。我每次提交表单时都会突然收到以下自定义错误消息:

header('HTTP/1.1 500 Our server is under maintenance!<br> If this error persists please contact us directly: <strong>something@test.com</strong>');

我已经在表单的字段中测试了php验证,这似乎工作正常。 我没有改变我的php或ajax逻辑或html表单本身的任何内容。无法弄清楚它的错误。

这是我使用的php:

<?php
if($_POST)
{
    //check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
        die();
    } 


    //check $_POST vars are set, exit if any missing
    if(!isset($_POST["userName"]) || !isset($_POST["userLastName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userArrival"]) || !isset($_POST["userNumberPeople"]) 
    || !isset($_POST["userPickupLocation"]) || !isset($_POST["userRequest"]) || !isset($_POST["userTourSelection"]))
    {
        die();
    }

    //Sanitize input data using PHP filter_var().
    $user_Name              = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
    $user_LastName          = filter_var($_POST["userLastName"], FILTER_SANITIZE_STRING);
    $user_Email             = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
    $user_TourSelection     = filter_var($_POST["userTourSelection"], FILTER_SANITIZE_STRING);
    $user_Arrival           = filter_var($_POST["userArrival"], FILTER_SANITIZE_STRING);
    $user_NumberPeople      = filter_var($_POST["userNumberPeople"], FILTER_SANITIZE_STRING);
    $user_PickupLocation    = filter_var($_POST["userPickupLocation"], FILTER_SANITIZE_STRING);
    $user_Request           = filter_var($_POST["userRequest"], FILTER_SANITIZE_STRING);



     $to_Email       = "something@test.com"; //Replace with recipient email address
     $subject        = 'Tour request: '.$user_TourSelection.' '; //Subject line for emails


    //additional php validation
    if(strlen($user_Name)<2) // If length is less than 4 it will throw an HTTP error.
    {
        header('HTTP/1.1 500 Name is too short or empty!');
        exit();
    }
    if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
    {
        header('HTTP/1.1 500 Please enter a valid email address!');
        exit();
    }
    if(strlen($user_Request)<5) //check emtpy message
    {
        header('HTTP/1.1 500 Please explain in a few words how you would like us to assist you.');
        exit();
    }


    // message
$message = '<strong>Name:</strong> '.$user_Name.' '.$user_LastName.' <br><br>
            <strong>Date of Arrival:</strong> '.$user_Arrival.' <br><br>
            <strong>Tour:</strong> '.$user_TourSelection.' <br><br>
            <strong>Number of people:</strong> '.$user_NumberPeople.' <br><br>
            <strong>Pick-Up Location:</strong> '.$user_PickupLocation.' <br><br>
            <strong>Request:</strong> '.$user_Request.' 
            ';


//proceed with PHP email.
    $headers = 'From: '.$user_Email.'' . "\r\n" .
    $headers .='Reply-To: '.$user_Email.'' . "\r\n" ;
    $headers .= 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $headers .='X-Mailer: PHP/' . phpversion();

   @$sentMail = mail($to_Email, $subject, $message, $headers);

    if(!$sentMail)
    {
        header('HTTP/1.1 500 Our server is under maintenance!<br> If this error persists please contact us directly: <strong>something@test.com</strong>');
        exit();
    }else{
        echo 'Congratulations '.$user_Name .'! ';
        echo 'We have received your request and we will respond as soon as possible.';
    }
}
?>

这是JS

$(document).ready(function() {

    $("#submit_btn").click(function() { 
        //collect input field values
        var user_name       = $('input[name=firstName]').val(); 
        var user_lastname   = $('input[name=lastName]').val();
        var user_email      = $('input[name=email]').val();
        var user_numberpeople = $('select#numberofPeople').val();
        var user_pickuplocation = $('select#pickupLocation').val();
        var user_arrivaldate = $('input[name=arrivalDate]').val();
        var user_request    = $('textarea[name=request]').val();
        var user_tourselection = $('#tourSelection option:selected').val();

        //simple validation at client's end
        //we simply change border color to red if empty field using .css()
        var proceed = true;

       if(user_name==""){ 
            $('input[name=firstName]').addClass("required");
            proceed = false;
        }
        if(user_lastname==""){ 
            $('input[name=lastName]').addClass("required"); 
            proceed = false;
        }
        if(user_email=="") {    
            $('input[name=email]').addClass("required"); 
            proceed = false;
        }
        if(user_numberpeople=="") {    
            $('select#numberofPeople').addClass("required");
            proceed = false;
        }

        if(user_pickuplocation=="") {    
            $('select#pickupLocation').addClass("required"); 
            proceed = false;
        }


        if(user_arrivaldate=="") {    
            $('input[name=arrivalDate]').addClass("required"); 
            proceed = false;
        }

        if(user_request=="") {  
            $('textarea[name=request]').addClass("required"); 
            proceed = false;
        }

        if(user_tourselection=="") {  
            $('select#tourSelection').addClass("required"); 
            proceed = false;
        }



        //everything looks good! proceed...
        if(proceed){

            //deactivate button
            $("#reservation-form button#submit_btn").attr("disabled", "disabled").text('Processing...').addClass("processing-state");

            //data to be sent to server
            var post_data = {

                'userName':user_name, 
                'userLastName':user_lastname, 
                'userEmail':user_email, 
                'userNumberPeople':user_numberpeople, 
                'userPickupLocation':user_pickuplocation, 
                'userArrival':user_arrivaldate, 
                'userRequest':user_request, 
                'userTourSelection':user_tourselection
            };

            //Ajax post data to server
            $.post('http://www.myurl.com/reservation.php', post_data, function(data){  

                //load success message in #result div element, with slide effect.
                $("#result").hide().html('<span class="success">'+data+'</span>').slideDown();

                $('label').hide();
                $('select').hide();
                $('#reservation-form h2').hide();
                ga('send', 'event', 'tours', 'request-tour', 'Tour-Request-Complete');


            }).fail(function(err) {  //load any error data

                $("#reservation-form button#submit_btn").text('REQUEST FAILED...').removeClass("processing-state").addClass("fail-state");
                $("#result").hide().html('<div class="error">'+err.statusText+'</div>').slideDown();

                ga('send', 'event', 'tours', 'request-tour', 'Tour-Request-Error');

                $( "#reservation-form input, #reservation-form textarea" ).focus(function() {

                    $("#reservation-form button#submit_btn").removeAttr("disabled").text('SEND YOUR REQUEST').removeClass("fail-state");
                    $("#result").slideUp();

                }); 

            });
        }
    });


    //reset previously set border colors and hide all message on .keyup()
    $("input, textarea").keyup(function() { 
        $(this).removeClass("required"); 
    });


    $("select#tourSelection").change(function() {

        if( $("select#tourSelection").val() != '')

            {$("select#tourSelection").removeClass("required");
            }

    });


        $("select#numberofPeople").change(function() {

        if( $("select#numberofPeople").val() != '')

            {$("select#numberofPeople").removeClass("required");
            }

    });

        $("select#pickupLocation").change(function() {

        if( $("select#pickupLocation").val() != '')

            {$("select#pickupLocation").removeClass("required");
            }

    });




});

和HTML

<fieldset id="reservation-form">

<div id="result"></div>
    <h2>Please fill out the form</h2>

    <label for="firstName">
    <input type="text" name="firstName" id="firstName" placeholder="FIRST NAME" />
    </label>

    <label for="lastName">
    <input type="text" name="lastName" id="lastName" placeholder="LAST NAME" />
    </label>

    <label for="email">
    <input type="text" name="email" id="email" placeholder="EMAIL" />
    </label>

    <select id="tourSelection">
    <option value="">PLEASE SELECT YOUR TOUR</option>
    <option value="ATHENS TOUR">ATHENS TOUR</option>
    <option value="ATHENS and SOUNION TOUR">ATHENS &amp; SOUNION TOUR</option>
    <option value="ATHENS and CORINTH TOUR">ATHENS &amp; CORINTH TOUR</option>
    <option value="PELOPONNESE TOUR">PELOPONNESE TOUR</option>
    <option value="DELPHI TOUR">DELPHI TOUR</option>
    <option value="DELPHI and THERMOPYLAE TOUR">DELPHI &amp; THERMOPYLAE TOUR</option>
    <option value="VRAVRONA MARATHON and SOUNION TOUR">VRAVRONA MARATHON &amp; SOUNION</option>
    <option value="ATHENS HALF DAY TOUR">ATHENS HALF DAY TOUR</option>
    <option value="CORINTH TOUR">CORINTH TOUR</option>
    <option value="SOUNION TOUR">SOUNION TOUR</option>
    <option value="SOUNION SUNSET TOUR">SOUNION SUNSET TOUR</option>
    <option value="NAFPLIO TOUR">NAFPLIO TOUR</option>
    <option value="DELPHI and METEORA TOUR">DELPHI &amp; METEORA TOUR</option>
    <option value="ARGOLIDA and ANCIENT OLYMPIA TOUR">ARGOLIDA &amp; ANCIENT OLYMPIA TOUR</option>
    <option value="THREE DAY PELOPONNESE TOUR">THREE DAY PELOPONNESE TOUR</option>
    <option value="FOUR DAY PELOPONNESE TOUR">FOUR DAY PELOPONNESE TOUR</option>
    <option value="CUSTOM TOUR">CUSTOM TOUR</option>
    </select>


    <select id="numberofPeople">
        <option value="">TOTAL NUMBER OF PEOPLE IN YOUR PARTY</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="Over 8">Over 8</option>
    </select>


        <select id="pickupLocation">
         <option value="">SPECIFY PICK-UP LOCATION</option>
        <option value="Port">PORT</option>
        <option value="Airport">AIRPORT</option>
        <option value="Hotel">HOTEL</option>
        <option value="Other">OTHER</option>
        </select>




    <label for="arrivalDate">
    <input type="text" name="arrivalDate" id="arrivalDate" placeholder="DATE YOU WISH TO DO THE TOUR" />
    </label>

    <label for="request">
    <textarea name="request" id="request" placeholder="YOUR PERSONAL REQUEST"></textarea>
    </label>

    <label>
    <button class="submit_btn" id="submit_btn">SEND YOUR REQUEST</button>
    </label>
</fieldset>

问题是表单不会将数据发送到指定的电子邮件。它始终显示自定义错误消息。

非常感谢任何帮助。

谢谢!

php错误报告显示以下内容:

Array ( [type] => 8192 [message] => Directive 'register_globals' is deprecated in PHP 5.3 and greater [file] => Unknown [line] => 0 )

更新php_flag register_globals off添加到我的htaccess后,我不再收到php错误消息但仍未提交。继续从第72行加载自定义错误消息(php代码)。

2 个答案:

答案 0 :(得分:2)

邮件无法在行

中发送
@$sentMail = mail($to_Email, $subject, $message, $headers);

删除&#39; @&#39;字符,它可能会给你一个消息,为什么它没有发送。

可能存在的问题可能是您不允许从服务器发送邮件或者PHP的配置发生了变化!

编辑:要捕获错误消息,您应该使用error_get_last函数。请尝试在第72行添加print_r(error_get_last()); exit;

答案 1 :(得分:1)

问题是由电子邮件发送引起的。 检查邮件功能是否正常。问题可能出在服务器配置中。