通过Ajax到PHP验证脚本的jQuery Post

通过Ajax到PHP验证脚本的jQuery Post,php,jquery,ajax,validation,Php,Jquery,Ajax,Validation,我知道我可以在jQueryUI中使用表单验证插件,但为了教自己一些新技巧,我正在采用这种方法 我有一个jQuery脚本,它通过Ajax将表单发布到PHP脚本。然后,脚本验证输入并将JSON编码的字符串发送回脚本。此时,应根据状态将验证消息置于模式对话框中,然后打开以告知用户发生了什么 问题 脚本似乎正在返回“null”状态。在Chrome的JavaScript控制台中,单击表单的submit按钮后会出现以下行: Uncaught TypeError: Cannot read property '

我知道我可以在jQueryUI中使用表单验证插件,但为了教自己一些新技巧,我正在采用这种方法

我有一个jQuery脚本,它通过Ajax将表单发布到PHP脚本。然后,脚本验证输入并将JSON编码的字符串发送回脚本。此时,应根据状态将验证消息置于模式对话框中,然后打开以告知用户发生了什么

问题

脚本似乎正在返回“null”状态。在Chrome的JavaScript控制台中,单击表单的submit按钮后会出现以下行:

Uncaught TypeError: Cannot read property 'status' of null 
这是我的验证表单.js

$(document).ready(function() {
    $("#contact_submit").on("click", function(e){
        e.preventDefault();
        var dataString = $("#frm_contact").serialize();
        console.log(dataString);
        $.ajax({
            type: "POST",
            url: "contact.php",
            data: dataString,
            dataType: "json",
            cache: false,
            success: function(data){
                console.log(data);
                if(!data){
                    alert("null value returned");
                }else if(data.status > 0){
                    $("#response").dialog({
                        autoOpen: false,
                        modal: true,
                        height: 240,
                        width: 320
                    });

                    $("#response").dialog("open");
                };
            }
        });
    });
});
这里是contact.php

<?php
    if(isset($_POST['contact_submit'])){
        $name = trim($_POST['contact_name']);
        $name = ucwords($name);
        $email = trim($_POST['contact_email']);
        $email = strtolower($email);
        $dept = trim($_POST['contact_dept']);
        $dept = ucwords($dept);
        $notes = trim($_POST['contact_notes']);

        // Patterns and Comparison Qualifiers
            $name_pattern = "/^[a-z][a-z ]*$/i";
            $email_pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/";
            $avail_depts = array("General", "Sales", "Support");
            $notes_minlength = 25;
            $notes_maxlength = 500;

        if(!preg_match($name_pattern, $name)){
            $resp = array("status"=>1, "message"=>"Names may only contain letters and spaces");
        }else{
            if(!preg_match($name_pattern, $name)){
                $resp = array("status"=>2, "message"=>"Invalid e-mail address");
            }else{
                if(!in_array($dept, $avail_depts)){
                    $resp = array("status"=>3, "message"=>"Please select a department");
                }else{
                    if(strlen($notes) < $notes_minlength || strlen($notes) > $notes_maxlength){
                        $resp = array("status"=>4, "message"=>"Comments must be between 25 and 500 characters");
                    }else{
                        // Build the message and e-mail it
                            $to = "info@mydomain.com";
                            $headers = "From: ".$name." <".$email.">";
                            $message .= "Contact Form Submission\n";
                            $message .= "==========================\n\n";
                            $message .= "Contact Name: ".ucwords($name)."\n\n";
                            $message .= "Contact E-mail: ".$email."\n\n";
                            $message .= "Category: ".$dept."\n\n";
                            $message .= "Comments: ".$notes."\n\n";
                            $message .= "\n";

                            if(mail($to, $subject, $message, $headers)){
                                $resp = array("status"=>5, "message"=>"Thanks! We'll be in touch soon!");
                            }else{
                                $resp = array("status"=>6, "message"=>"Something went wrong, please try again");
                            }
                    }
                }
            }
        }
    }

    echo json_encode($resp);
?>
正如您所看到的,它应该在不在25到500个字符之间的注释上失败,并返回正确的错误消息。相反,我仍然看到“无法读取(null)的属性'status'”

更新2

下面就是我在JavaScript控制台中看到的内容

更新3

我决定删除prevent默认值,并通过传统的
语句直接发布到联系人页面,该语句包含
method=“post”action=“contact.php”
,以查看脚本本身是否正确生成JSON字符串,并且是否正确;以下是我最近一次测试中生成的内容:

{“状态”:4,“消息”:“评论必须在25到500个字符之间”}

因此,要么没有将其发送回ajax处理程序,要么缺少其他内容

更新4

我修改了脚本以处理空值,并在没有传递值时提醒我。因此,现在很明显,脚本没有将json字符串传递回ajax调用,即使在更新3中,我已经验证它将json字符串回显到屏幕上。我不知所措。。。(更新上面的脚本)

更新5


所以我取得了一些进展。结果是返回空值,因为在我的PHP脚本中,我正在检查是否设置了提交按钮以及
$\u POST
数组的一部分。但是,因为我通过jQuery阻止表单的默认操作,所以它不会被传递。在
dataString
中只发送序列化的表单值。现在我在控制台中得到了我期望的错误,但是我没有得到模态对话框显示。戏剧还在继续。

大多数浏览器支持JSON.parse(),它是在ECMA-262第5版(JS所基于的规范)中定义的。它的用法很简单:

var json='{“结果”:true,“计数”:1}', obj=JSON.parse(JSON)

警报(目标计数)

对于不需要的浏览器,可以使用json2.js实现它

如前所述,您已经在使用jQuery,有一个$.parseJSON函数可以映射到JSON.parse(如果可用)或旧浏览器中的一种eval形式。 但是,这会执行附加的、不必要的检查,这些检查也是由JSON.parse执行的,因此,为了获得最佳的全面性能,我建议像这样使用它:

var json='{“结果”:true,“计数”:1}', obj=JSON&&JSON.parse(JSON)| |$.parseJSON(JSON)


这将确保您立即使用本机JSON.parse,而不是让jQuery在将字符串传递给本机解析函数之前对其执行健全性检查。

下面我已经提到了一些要点,请尝试解决您的问题 1.更改您的方法以获取并尝试


2.将die()放在最后一个echo之后,检查输出的确切内容。

因此,在经过数小时的调整、测试和拔出头发后,这是工作脚本

jQuery

$(document).ready(function() {
    $("#contact_submit").on("click", function(e){
        e.preventDefault();
        var dataString = $("#frm_contact").serialize();
        console.log(dataString);
        $.ajax({
            type: "POST",
            url: "contact.php",
            data: dataString,
            dataType: "json",
            cache: false,
            success: function(data){
                console.log(data);
                if(!data){
                    alert("null value returned");
                }else if(data.err > 0){
                    var $response = $("<div></div>")
                    .dialog({
                        resizable: false,
                        autoOpen: false,
                        modal: true,
                        height: "auto",
                        width: "auto",
                        buttons: { "ok": function() { $(this).dialog("close"); } }
                    });
                    $response.html("Error:");
                    $response.html(data.message);
                    $response.dialog("open");
                    $(".ui-dialog-titlebar").hide();
                };
            }
        });
    });
});
$(文档).ready(函数(){
$(“#联系#u提交”)。在(“单击”上,功能(e){
e、 预防默认值();
var dataString=$(“#frm_contact”).serialize();
log(数据字符串);
$.ajax({
类型:“POST”,
url:“contact.php”,
数据:dataString,
数据类型:“json”,
cache:false,
成功:功能(数据){
控制台日志(数据);
如果(!数据){
警报(“返回空值”);
}否则如果(data.err>0){
变量$response=$(“”)
.对话({
可调整大小:false,
自动打开:错误,
莫代尔:是的,
高度:“自动”,
宽度:“自动”,
按钮:{“确定”:函数(){$(this).dialog(“close”);}
});
$response.html(“错误:”);
$response.html(data.message);
$response.dialog(“打开”);
$(“.ui对话框标题栏”).hide();
};
}
});
});
});
对于PHP脚本,我必须稍微调整它,以便正确地处理它

<?php
        $name = trim(urldecode($_POST['contact_name']));
        $name = ucwords($name);
        $email = trim(urldecode($_POST['contact_email']));
        $email = strtolower($email);
        $dept = trim($_POST['contact_dept']);
        $dept = ucwords($dept);
        $notes = trim(urldecode($_POST['contact_notes']));

        // Patterns and Comparison Qualifiers
            $name_pattern = "/^[a-z][a-z ]*$/i";
            $email_pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/";
            $avail_depts = array("General", "Sales", "Support");
            $notes_minlength = 25;
            $notes_maxlength = 500;

        if(!preg_match($name_pattern, $name)){
            $resp = array("err"=>1, "message"=>"Names may only contain letters and spaces");
        }else{
            if(!preg_match($email_pattern, $email)){
                $resp = array("err"=>2, "message"=>"Invalid e-mail address");
            }else{
                if(!in_array($dept, $avail_depts)){
                    $resp = array("err"=>3, "message"=>"Please select a department");
                }else{
                    if(strlen($notes) < $notes_minlength || strlen($notes) > $notes_maxlength){
                        $resp = array("err"=>4, "message"=>"Comments must be between 25 and 500 characters");
                    }else{
                        // Build the message and e-mail it
                            $headers = "From: ".$name." <".$email.">";
                            $message .= "Contact Form Submission\n";
                            $message .= "==========================\n\n";
                            $message .= "Contact Name: ".ucwords($name)."\n\n";
                            $message .= "Contact E-mail: ".$email."\n\n";
                            $message .= "Category: ".$dept."\n\n";
                            $message .= "Comments: ".$notes."\n\n";
                            $message .= "\n";

                            if(mail($to, $subject, $message, $headers)){
                                $resp = array("err"=>5, "message"=>"Thanks! We'll be in touch soon!");
                            }else{
                                $resp = array("err"=>6, "message"=>"Something went wrong, please try again");
                            }
                    }
                }
            }
        }
    echo json_encode($resp);
?>

可以添加行
console.log(dataString)在上面
$.ajax
这样我们就可以看到发送到那里的内容了?你的控制台说了什么??看看它是否给出了有效的json响应。我已经为OPI添加了一个更新。我还修改了脚本,请参见上面的更新。更改为GET不会产生任何效果。还将die()添加到echo json_encode($resp)之后;什么也没做。我也修改了脚本,请看上面的更新。
<?php
        $name = trim(urldecode($_POST['contact_name']));
        $name = ucwords($name);
        $email = trim(urldecode($_POST['contact_email']));
        $email = strtolower($email);
        $dept = trim($_POST['contact_dept']);
        $dept = ucwords($dept);
        $notes = trim(urldecode($_POST['contact_notes']));

        // Patterns and Comparison Qualifiers
            $name_pattern = "/^[a-z][a-z ]*$/i";
            $email_pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/";
            $avail_depts = array("General", "Sales", "Support");
            $notes_minlength = 25;
            $notes_maxlength = 500;

        if(!preg_match($name_pattern, $name)){
            $resp = array("err"=>1, "message"=>"Names may only contain letters and spaces");
        }else{
            if(!preg_match($email_pattern, $email)){
                $resp = array("err"=>2, "message"=>"Invalid e-mail address");
            }else{
                if(!in_array($dept, $avail_depts)){
                    $resp = array("err"=>3, "message"=>"Please select a department");
                }else{
                    if(strlen($notes) < $notes_minlength || strlen($notes) > $notes_maxlength){
                        $resp = array("err"=>4, "message"=>"Comments must be between 25 and 500 characters");
                    }else{
                        // Build the message and e-mail it
                            $headers = "From: ".$name." <".$email.">";
                            $message .= "Contact Form Submission\n";
                            $message .= "==========================\n\n";
                            $message .= "Contact Name: ".ucwords($name)."\n\n";
                            $message .= "Contact E-mail: ".$email."\n\n";
                            $message .= "Category: ".$dept."\n\n";
                            $message .= "Comments: ".$notes."\n\n";
                            $message .= "\n";

                            if(mail($to, $subject, $message, $headers)){
                                $resp = array("err"=>5, "message"=>"Thanks! We'll be in touch soon!");
                            }else{
                                $resp = array("err"=>6, "message"=>"Something went wrong, please try again");
                            }
                    }
                }
            }
        }
    echo json_encode($resp);
?>