联系表单 - 将变量从PHP传递到jQuery

时间:2017-09-06 23:30:56

标签: php jquery html ajax

[我怀疑手头的问题与如何将php数组传递给jQuery有关,如果情况不是这样我为误导性标题道歉]

下面的联系表格正在运作 - 除非我提交表格的数据时,有时一个字段始终保持其红色边框表示缺少输入,即使它实际上有数据。

详细说明:我有一个只运行php的解决方案,但在提交时会导致页面重新加载,我想避免。经过一些研究,似乎我需要php / jQuery / ajax来异步执行这些操作并保持在同一个站点上。

所需行为 因此,有三个必需的输入字段,名称,电子邮件和消息,如果省略任何一个,它应该收到一个红色边框,没有发送电子邮件。

实际行为 例如,如果仅填写并提交了名称和消息,则空电子邮件字段将显示为红色。 但是,如果提供了(有效)电子邮件,则第二个提交操作不会删除电子邮件字段周围的红色边框。

我知道javascript和朋友是客户端语言,PHP在服务器端处理。提交表单后,.ajax函数获取序列化的表单值,使用“POST”将其填入php脚本并等待服务器在内部调用我们.done()

这就是我迷失的地方 - 如何在jQuery中使用php数组?

E.g。无论如何,这条线永远不会到达:

console.log("All fields filled and valid"); 

index.html:

<!DOCTYPE html>
<head>
<meta http-equiv="content-type" content="text/html" charset="UTF-8" />

<script src="jquery-1.12.4.min.js"></script>
<script src="verify.js"></script>

    <style>
        .input-error
        {
            border: 2px solid red;
        }
    </style>        

    <script>
        $(document).ready(function()                // Wait until website (DOM) is completely loaded
        {    
            /* Page top */
            $('#pagetop').click(function()
            {
                console.log(this);
                $('body, html').animate({scrollTop: '0px'}, 600);
                return false;
            });     
        });
    </script>

</head>

<body>  
    <!-- action is left blank as process.php is called from verify.js -->
    <form action="" method="POST" id="contactForm">     

        <label for="company">Company</label>    
        <br>                
        <input type="text" style="width: 904px; height: 24px;" id="company" name="company" value="">
        <br><br>                            

        <label for="name">Name *</label>    
        <br>                
        <input type="text" style="width: 904px; height: 24px;" id="name" name="user_name" value="">
        <br><br>            

        <label for="email">Email *</label>  
        <br>            
        <input type="text" style="width: 904px; height: 24px;" id="email" name="user_email" value="">
        <br><br>            

        <label for="message">Message *</label>
        <br>
        <textarea style="width: 904px; resize: none;" rows="9" id="message" name="user_message"></textarea>
        <br><br>                                

        <input type="submit" id="submit" name="submit" value="Send">
        <br><br>

    </form>
</body>

verify.js

$(document).ready(function() 
{
    // process the form
    $('#contactForm').submit(function(event) 
    {               
        //$('#name, #email, #message').removeClass('input-error'); 

        // process the form
        $.ajax(
        {
            type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
            url         : 'process.php', // the url where we want to POST
            data        : $('#contactForm').serialize(),
            dataType    : 'json', // what type of data do we expect back from the server
            encode      : true
    })
        // using the done promise callback
        .done(function(data) 
        {
            // log data to the console so we can see
            console.log(data);              

             if (data.errors.name) 
             {
                 console.log("Name missing"); 
                 $('#name').addClass('input-error'); 
             }
             else
             {
                 $('#name').removeClass('input-error'); 
             }

             // handle errors for email
             if (data.errors.email) 
             {
                 console.log("Email missing or invalid"); 
                 $('#email').addClass('input-error'); 
             }
             else
             {
                 $('#email').removeClass('input-error'); 
             }

             // handle errors for message
             if (data.errors.message) 
             {
                 console.log("Message missing"); 
                 $('#message').addClass('input-error'); 
             }
             else
             {
                 $('#message').removeClass('input-error'); 
             }


             if(data.input_valid == true)
             {          
                 console.log("All fields filled and valid"); 
                 alert('success');      
             }      
        });

        // stop the form from submitting the normal way and refreshing the page
        event.preventDefault();
    });

});

process.php

<?php

    $errors         = array();      // array to hold validation errors
    $data           = array();      // array to pass back data

    // Sanitize input variables 
    $company = test_input($_POST['company']);
    $name = test_input($_POST['user_name']);
    $email = test_input($_POST['user_email']);
    $message = test_input($_POST['user_message']);


    // Validate the variables 
    // If any of these variables don't exist, add an error to our $errors array

    if (empty($name))       
        $errors['name'] = 'Name is required.';

    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL))
        $errors['email'] = 'Valid Email is required.';

    if (empty($message))
        $errors['message'] = 'Message is required.';


    $from = '--- Contact Form ---'; 
    $to = 'some@mail.com'; 
    $subject = 'Message from Contact Form'; 
    $body = "From: $name\nCompany: $company\nE-Mail: $email\nMessage:\n\n$message";

    // return a response ===========================================================

    // if there are any errors in our errors array, return a success boolean of false
    if(!empty($errors)) 
    {
        // if there are items in our errors array, return those errors
        $data['input_valid'] = false;
        $data['errors']  = $errors;
    } 
    else 
    {
        // If there are no errors process our form, then return a message
        $data['input_valid'] = true;

        if(mail($to, $subject, $body, $from)) 
        {
            $data['message'] = 'Thank you for your message!';
            $data['mail_sent'] = true;
        } 
        else    
        {
            $data['message'] = 'Message could not be sent - please try again later.';
            $data['mail_sent'] = false;
        }
    }

    // return all our data to an AJAX call
    echo json_encode($data);


    // Convert special characters to html entities to prevent XSS attacks
    // Also remove white-space and backslashes
    function test_input($val) 
    {
        $val = trim($val);
        $val = stripslashes($val);
        $val = htmlspecialchars($val);
        return $val;
    }
?>

2 个答案:

答案 0 :(得分:1)

如果所有验证都在您的php脚本中传递,则永远不会定义data['errors']。这可能会导致在您编写时在javascript中抛出错误(您可以在浏览器控制台中看到):

if (data.errors.name) 

data.errors将在javascript中评估为undefined,当您尝试访问类似undefined的{​​{1}}属性时,它将抛出错误并停止脚本。

要解决此问题,您可能只需要在php脚本中定义错误,(尽管我并非100%确定JSON方法不会遗漏一个空数组......)。尝试在您的PHP脚本中执行此操作:

data.errors.name

答案 1 :(得分:0)

修改

我不知道它是否适用于您的jquery版本,但万一它不是,请将此代码放在标题中:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

我使用了以下代码并且它有效。发送电子邮件而无需更改PHP代码:

$(document).ready(function()  {
    $('#contactForm').submit(function(event)  {
        $.ajax({
            type: 'POST',
            url: 'process.php',
            data: $('#contactForm').serialize(),
            dataType: 'json',
            encode: true
        })
        .done(function(data)  {
            console.log(data);
            if(data.input_valid == true) {
                console.log("All fields filled and valid");
                // If the function is a success remove error classes from all fields
                // you can either place the below code above the alert so that it happens
                // before you get the success message, or after.
                $('#name').removeClass('input-error');
                $('#email').removeClass('input-error');
                $('#message').removeClass('input-error');
                alert('success');
            } else {
                if (data.errors.name)  {
                    console.log("Name missing");
                    $('#name').addClass('input-error');
                } else {
                    $('#name').removeClass('input-error');
                }
                if (data.errors.email)  {
                    console.log("Email missing or invalid");
                    $('#email').addClass('input-error');
                } else {
                    $('#email').removeClass('input-error');
                }
                if (data.errors.message) {
                    console.log("Message missing");
                    $('#message').addClass('input-error');
                } else {
                    $('#message').removeClass('input-error');
                }
            }
        });
        event.preventDefault();
    });
});