2014-02-26 30 views
0

我知道我可以使用帶有jQuery UI的表單驗證插件,但爲了教我自己一些新的技巧,我正在採用這種方法。jQuery通過Ajax發佈到PHP驗證腳本

我有一個通過Ajax將表單發佈到PHP腳本的jQuery腳本。然後腳本驗證輸入並將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 = "[email protected]"; 
          $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); 
?> 

UPDATE 1

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

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

正如你可以看到它應該失敗的筆記不在25到500個字符之間,並返回正確的錯誤信息。相反,我仍然看到

更新2

這裏的 「(空)無法讀取屬性 '狀態'」 正是我在JavaScript控制檯 JavaScript Console

更新3

我決定刪除防止默認設置,並通過傳統的<form>聲明直接發佈到聯繫頁面,該聲明包括method="post" action="contact.php"來查看腳本本身是否正確生成了JSON字符串,並且是;這裏就是它在我最近的測試中產生:

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

因此,無論它不發送回阿賈克斯處理程序或別的東西丟失。

UPDATE 4

我修改的腳本來處理空值,如果沒有值傳遞提醒我。所以現在很明顯,即使在更新3中,我已經驗證過它會將一個json字符串傳遞迴ajax調用,但它仍然會在屏幕上回顯一個json字符串。我不知所措......(以上更新腳本)

UPDATE 5

所以我已經取得了一些進展。事實證明,返回null是因爲在我的PHP腳本中,我檢查提交按鈕是否已設置,並且是否爲$_POST數組的一部分。但是,因爲我通過jQuery阻止了表單的默認動作,所以沒有被傳遞。僅在dataString中發送序列化的表單值。所以現在我在控制檯中收到了錯誤,但我沒有看到模式對話框。戲劇繼續。

+1

你可以在''.ajax'上面添加'console.log(dataString)'這一行嗎,這樣我們就可以看到那裏發送了什麼? – anthonygore

+0

你的控制檯說什麼?看看它給予有效的JSON響應 –

+0

當然。我已經添加了更新到OP – rws907

回答

0

所以經過更多的時間調整,測試和拉出我的頭髮,這裏是工作腳本。

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

一切工作完美,模式警報和所有的用戶。感謝那些試圖幫助的人!

0

大多數瀏覽器都支持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在將字符串傳遞給本機解析函數之前對其進行完整性檢查。

0

下面我提到了一些要點,試着解決你的問題 1.改變你的方法去試試。

2.在最後一個回聲後輸入die()並檢查確切的輸出。

+0

更改爲GET什麼都不做。在echo json_encode($ resp)之後加入die();什麼也沒做。 – rws907

+0

我也修改了腳本,請參閱上面的更新。 – rws907