2014-02-26 3 views
0

jQuery UI와 양식 유효성 검사 플러그인을 사용할 수 있다는 것을 알고 있지만 새로운 방법을 가르쳐주기 위해이 방법을 사용하고 있습니다.jQuery PHP 유효성 검사 스크립트 Ajax를 통해 게시

저는 Ajax를 통해 PHP 스크립트에 양식을 게시하는 jQuery 스크립트를 가지고 있습니다. 그런 다음 스크립트는 입력을 확인하고 JSON 인코딩 된 문자열을 스크립트로 다시 보냅니다. 이 시점에서 상태에 따라 유효성 검사 메시지를 모달 대화 상자에 배치 한 다음 열어서 사용자에게 알려줍니다.

문제는

이 스크립트는 "널 (null)"상태를 반환하는 것 같다. 크롬의 자바 스크립트에 다음 줄을 콘솔에서하는 양식의 제출 버튼을 클릭하면 나타납니다

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

업데이트 1

console.log (dataString); 맺는 콘솔에서 다음

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

당신이 25 명 500 자 사이에없는 노트에 실패하고 적절한 오류 메시지를 반환해야했습니다 볼 수 있듯이. 대신 난 아직도 자바 스크립트 콘솔 JavaScript Console

UPDATE 3

에서 볼을 정확히

UPDATE 여기에 2

은 "(널)의 속성을 읽을 수없는 '상태'"입니다 참조

기본 방지를 제거하고 실제로 <form> 문을 사용하여 연락처 페이지에 직접 게시하려면문구가 포함되어 있습니다. 10 스크립트 자체가 JSON 문자열을 제대로 생성하고 있는지 확인합니다.

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

을 그러니 그것은 다시 아약스 핸들러에 보내기 아니에요 또는 뭔가 다른 누락 : 여기가 내 가장 최근의 테스트에서 생성 된 것입니다. 4

UPDATE 내가 널 값을 처리하고 값이 전달되지 않은 경우 나에게 경고하기 위해 스크립트를 수정했습니다. 따라서 업데이트 3에서 스크린에 하나가 울리는 것을 확인했지만 스크립트에서 json 문자열을 다시 아약스 호출로 전달하지 않는다는 것이 확실합니다. 나는 ... 손실에 (위의 업데이트 스크립트) 5

그래서 나는 약간의 진전을했습니다

UPDATE입니다.내 PHP 스크립트에서 submit 버튼이 설정되어 있고 $_POST 배열의 일부인지 확인했기 때문에 null이 반환되는 것으로 나타났습니다. 하지만 jQuery를 통해 양식의 기본 동작을 방해하기 때문에 전달되지 않습니다. 직렬화 된 양식 값만 dataString에 전송됩니다. 이제 예상대로 콘솔에서 오류가 다시 발생하지만 모달 대화 상자가 표시되지 않습니다. 드라마는 계속됩니다.

+1

'$ .ajax'보다'console.log (dataString);'줄을 추가하여 거기에 무엇이 보내지는지 볼 수 있습니까? – anthonygore

+0

당신의 콘솔이 뭐라고하니 ?? 그것의 유효한 json 응답을주는 경우에 –

+0

확실히보십시오. OP – rws907

답변

관련 문제