PHP& jQuery联系表单错误

时间:2015-03-05 18:29:51

标签: javascript php jquery html ajax

我正在尝试使用jQuery和PHP创建一个ajax联系表单,但是我被卡住了。

这是我的代码:

我的HTML代码(只是表单)

<div id="contact" class="request-info clearfix">
    <div class="full-row">
        <div id="result"></div>
        <label for="cat">Please select one:</label>
        <div class="input-select">
            <select name="cat" id="cat" class="postform">
                <option value="-1">-- select --</option>
                  <option value="1">1st</option>
                  <option value="2">2nd</option>
                  <option value="3">3rd</option>
                  <option value="4">4th</option>
                  <option value="5">5th</option>
            </select>
        </div>
    </div>

    <div class="full-row">
        <label for="yourname">Name:</label>
        <input type="text" id="yourname" name="yourname">
    </div>

    <div class="full-row">
        <label for="phone-no">Phone:</label>
        <input type="text" id="phone-no" name="phone-no">
    </div>

    <div class="full-row">
        <label for="email-id">Email:</label>
        <input type="text" id="email-id" name="email-id">
    </div>


    <div class="full-row">
    <button id="submit_btn" class="mainBtn pull-right" type="submit" name="submit">Submit Request</button>
        </div>
    </div>

JS

$(document).ready(function() {
$("#submit_btn").click(function() {

    //Get input field values
    var form_cat       = $("#cat").val();
    var form_yourname  = $('input[name=yourname]').val();
    var form_phone     = $('input[name=phone-no]').val();
    var form_email     = $('input[name=email-id]').val();


    // Checks if all fields are entered
    var proceed = true;

    if(form_cat=="-1"){
        $('#cat').css('border-color','red');
        proceed = false;
    }
    if(form_yourname==""){
        $('input[name=yourname]').css('border-color','red');
        proceed = false;
    }
    if(form_phone==""){
        $('input[name=phone-no]').css('border-color','red');
        proceed = false;
    }

    if(form_email=="") {
        $('input[name=email-id]').css('border-color','red');
        proceed = false;
    }

    // Check if we can proceed
    if(proceed)
    {
        // Data to be sent to server
        post_data = {   'formCat':form_cat,
                        'userName':form_yourname,
                        'userPhone':form_phone,
                        'userEmail':form_email
                    };

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

            // Load json data from server and output message
            if(response.type == 'error')
            {
                output = '<div class="alert alert-danger">'+response.text+'</div>';
            }else{

                output = '<div class="alert alert-success">'+response.text+'</div>';

                // Reset values in all input fields
                $('#contact input').val('');
                $('#contact select').val('');
            }

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

    }
});

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

});

form.php的

<?php
if($_POST)
{
    $to_Email       = "mail@mail.com"; 
    $subject        = 'Contact Form';


    //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);
    }

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

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

    //additional php validation
    if(strlen($user_Name)<4)
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Name field is empty! Please enter something.'));
        die($output);
    }
    if(strlen($user_Phone)<4)
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Phone number is too short or empty!'));
        die($output);
    }
    if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL))
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
        die($output);
    }

    //proceed with PHP email.
    $headers = 'From: '.$user_Email.'' . "\r\n" .
    'Reply-To: '.$user_Email.'' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

    // send mail
    $sentMail = @mail($to_Email, $subject .'  -  Email sent by: '.$user_Name, $headers);

    if(!$sentMail)
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Could not send mail.'));
        die($output);
    }else{
        $output = json_encode(array('type'=>'message', 'text' => 'Hello '.$user_Name .' thank you for your message.'));
        die($output);
    }
}

&GT;

我不知道我做错了什么。我希望有人可以帮助我。

提前致谢!

2 个答案:

答案 0 :(得分:0)

那可能是因为你没有停止上一次活动。您应该调用event.preventDefault(),这将阻止正在执行提交表单事件。

试试这个:

$(document).ready(function() {
    $("#submit_btn").click(function(event) {
        event.preventDefault();

...

答案 1 :(得分:0)

请改为尝试:

$(document).ready(function() {
$("#submit_btn").click(function() {

//Get input field values
var form_cat       = $("#cat").val();
var form_yourname  = $('input[name=yourname]').val();
var form_phone     = $('input[name=phone-no]').val();
var form_email     = $('input[name=email-id]').val();


// Checks if all fields are entered
var proceed = true;

if(form_cat=="-1"){
    $('#cat').css('border-color','red');
    proceed = false;
}
if(form_yourname==""){
    $('input[name=yourname]').css('border-color','red');
    proceed = false;
}
if(form_phone==""){
    $('input[name=phone-no]').css('border-color','red');
    proceed = false;
}

if(form_email=="") {
    $('input[name=email-id]').css('border-color','red');
    proceed = false;
}


post_data = {   'formCat':form_cat,
                        'userName':form_yourname,
                        'userPhone':form_phone,
                        'userEmail':form_email
                    };


// Check if we can proceed
if(proceed)
{
$.ajax({
            url: '/form.php',
            type: 'POST',
            data: post_data,
            cache: false,
            dataType: 'json',
            contentType: 'application/json',
            success: function(){
              //Success message
            },
            error: function(){

                //Error message

                // Reset values in all input fields
                $('#contact input').val('');
                $('#contact select').val('');
});
}

return false;
    });
});