我的联系表格正在运行,但不会显示成功消息

时间:2014-06-21 22:33:57

标签: php jquery ajax forms

我的联系表单正在运行,但成功消息并未显示。另一位开发人员编写了PHP代码但我做了一些jQuery并且它不会显示我的消息。我很确定问题出在jQuery上。我对这行代码感到特别困惑......

 $("#result").hide().html(output).slideDown();
            }, 'json');
        }

我认为你会想要使用.show(),因为需要#result才能显示html,但似乎并没有这样做。完整代码如下。

$(function(){
    $(".btn").click(function() {
        //get input field values
        var user_name       = $('input[name=name]').val(),
            user_email      = $('input[name=email]').val(),
            user_message    = $('textarea[name=message]').val(),
            proceed = true;

        //simple validation at client's end
        //we simply change border color to red if empty field using .css()
        if(user_name===""){
            $('input[name=name]').css('border','2px solid red').after('<p class="error-msg">(What\'s your name?)</p>');
            proceed = false;
        }
        if(user_email===""){
            $('input[name=email]').css('border','2px solid red').after('<p class="error-msg">(Please provide a valid email)</p>');
            proceed = false;
        }

        if(user_message==="") {
            $('textarea[name=message]').css('border','2px solid red').after('<p class="error-msg">(Please let me know what your inquiry is about)</p>');
            proceed = false;
        }

        //everything looks good! proceed...
        if(proceed)
        {
            //data to be sent to server
            post_data = {'userName':user_name, 'userEmail':user_email, 'userMessage':user_message};

            //Ajax post data to server
            $.post('../../contact-form.php', post_data, function(response){

                //load json data from server and output message
                if(response.type === 'error')
                {
                    output = '<div class="error">'+response.text+'</div>';

                }else{

                    output = '<div class="success">'+response.text+'</div>';
                    alert('Thanks for the message');

                    //reset values in all input fields
                    $('.form-container input').val('');
                    $('.form-container textarea').val('');
                }

                $("#result").hide().html(output).slideDown();
            }, 'json');
        }
    });

    //reset previously set border colors and hide all message on .keyup()
    $(".form-container input, .form-container textarea").keyup(function() {
        $(".form-container input, .form-container textarea").css('border-color','');
        $("#result").slideUp();
    });

});

PHP代码

<?php
 if($_POST)

{          $ to_Email =&#34; alexechaparro@gmail.com" ;; //替换收件人电子邮件地址          $ subject =&#39; alexsdogvacay.com&#39 ;; //电子邮件的主题行

//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {

    //exit script outputting json data
    $output = json_encode(
    array(
        'type'=>'error',
        'text' => 'Request must come from Ajax'
    ));

    die($output);
}


var_dump($_REQUEST);
//check $_POST vars are set, exit if any missing
if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userMessage"]))
{
    echo $_POST["userName"];
    $output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
    die($output);
}

//Sanitize input data using PHP filter_var().
$user_Name        = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_Email       = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Message     = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);

//additional php validation
if(strlen($user_Name)<4) // If length is less than 4 it will throw an HTTP error.
{
    $output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
    die($output);
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
{
    $output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
    die($output);
}

if(strlen($user_Message)<5) //check emtpy message
{
    $output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
    die($output);
}

//proceed with PHP email.

/*
Incase your host only allows emails from local domain,
you should un-comment the first line below, and remove the second header line.
Of-course you need to enter your own email address here, which exists in your cp.
*/
//$headers = 'From: your-name@YOUR-DOMAIN.COM' . "\r\n" .
$headers = 'From: '.$user_Email.'' . "\r\n" . //remove this line if line above this is un-commented
'Reply-To: '.$user_Email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

    // send mail
$sentMail = @mail($to_Email, $subject, $user_Message .'  -'.$user_Name, $headers);

if(!$sentMail)
{
    $output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
    die($output);
}else{
    $output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .' Thank you for your email. I will get back to you as soon as possible.'));
    die($output);
}

} ?&GT;

2 个答案:

答案 0 :(得分:0)

所以,令人困惑的代码行:$('#result').hide().html().slideDown();有效。无需改变它。我看到的一个问题是,您的变量output未被var定义,使其成为全局变量。

除此之外,php代码似乎使用die函数杀死了成功响应,但是它并没有向输出返回任何内容。改变这个:

if(!$sentMail)
{
    $output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
    die($output);
}else{
    $output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .' Thank you for your email. I will get back to you as soon as possible.'));
    die($output);
}

TO:

if(!$sentMail)
{
    $output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
}else{
    $output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .' Thank you for your email. I will get back to you as soon as possible.'));
}
echo $output;

希望这有帮助!

Ť

答案 1 :(得分:0)

这是我第二次因为我的HTML而被烧毁。以前我的HTML是......

         <form id="contact_form">
            <div id="result"></div>
            <div class="form-group">
                <label for="name" id="name">Name</label>
                <input type="text" name="name" class="form-control" id="exampleInputName" placeholder="Name" required>
            </div>
            <div class="form-group">
                <label for="Email" id="email">Email address</label>
                <input type="email" name="email" class="form-control" id="exampleInputEmail1" placeholder="Email" required>
            </div>

            <div class="form-group">
                <label for="Message" id="message">Message</label>
                <textarea rows="4" name='message'class="form-control"  placeholder="Message" required></textarea>
            </div>
            <div><span>&nbsp;</span>
                <input type="button" class="btn btn-default" id='submit_btn' value="Submit">
            </div>
        </form>

我所做的就是将我的表单更改为字段集并输入

 <button class="btn btn-default" id="submit_btn">Submit</button>

老实说,我不确定为什么要修复它,但确实如此。