簡體   English   中英

jQuery通過Ajax發布到PHP驗證腳本

[英]jQuery Post via Ajax to PHP Validation Script

我知道我可以將表單驗證插件與jQuery UI一起使用,但是為了自學,我采用了這種方法。

我有一個jQuery腳本,它通過Ajax將表單發布到PHP腳本。 然后,腳本會驗證輸入,並將JSON編碼的字符串發送回腳本。 此時,應根據狀態將驗證消息放入模式對話框中,然后打開以告知用戶發生了什么。

問題

腳本似乎返回“空”狀態。 在Chrome的JavaScript控制台中,單擊表單的“提交”按鈕后,將出現以下行:

Uncaught TypeError: Cannot read property 'status' of null 

這是我的validate_form.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);
?>

更新1

添加console.log(dataString); 在控制台中產生以下內容:

contact_name=Test&contact_email=testaccount%40mydomain.com&contact_dept=general&contact_notes=this+is+a+test+

如您所見,如果注釋中的字符數介於25到500個字符之間,它應該會失敗,並返回正確的錯誤消息。 相反,我仍然看到“無法讀取(null)的屬性'status'”

更新2

這正是我在JavaScript控制台中看到的 JavaScript控制台

更新3

我決定刪除阻止默認值,並通過傳統的<form>語句直接將其直接發布到聯系頁面,該語句包括method="post" action="contact.php"以查看腳本本身是否正確生成了JSON字符串並它是; 這是我最近一次測試產生的結果:

{"status":4,"message":"Comments must be between 25 and 500 characters"}

因此,要么沒有將其發送回ajax處理程序,要么缺少其他內容。

更新4

我修改了腳本以處理空值,並在未傳遞任何值時提醒我。 因此,很明顯,盡管在更新3中,我已驗證腳本正在向屏幕回顯一個腳本,但該腳本並未將json字符串傳遞回ajax調用。 我很茫然...(上面的更新腳本)

更新5

所以我取得了一些進展。 事實證明,返回了null,因為在我的PHP腳本中,我正在檢查是否設置了$_POST按鈕以及$_POST數組的一部分。 但是,由於我正在阻止通過jQuery進行表單的默認操作,因此未傳遞該默認操作。 dataString僅發送序列化的表單值。 因此,現在我在控制台中收到了我期望的錯誤,但沒有出現模式對話框。 戲劇繼續。

大多數瀏覽器都支持JSON.parse(),這是在ECMA-262第5版(JS所基於的規范)中定義的。 它的用法很簡單:

var json ='{“ result”:true,“ count”:1}',obj = JSON.parse(json);

alert(obj.count);

對於沒有的瀏覽器,您可以使用json2.js來實現。

如前所述,您已經在使用jQuery,有一個$ .parseJSON函數可映射到JSON.parse(如果可用),或者在較舊的瀏覽器中以eval的形式存在。 但是,這將執行JSON.parse也執行的其他不必要的檢查,因此為了獲得最佳的全面性能,我建議像這樣使用它:

var json ='{“ result”:true,“ count”:1}',obj = JSON && JSON.parse(json)|| $ .parseJSON(json);

這將確保您立即使用本機JSON.parse,而不是讓jQuery在將字符串傳遞給本機解析函數之前對字符串進行完整性檢查。

下面,我提到了一些要點,請嘗試一下以解決您的問題:1.更改獲取方法並嘗試。

2.在最后一次回聲之后放入die()並檢查確切的輸出。

因此,經過幾個小時的調整,測試並拔出頭發后,這是工作腳本。

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

對於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);
?>

一切運行正常,模式警報,一切對用戶有效。 感謝那些試圖提供幫助的人!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM