2013-02-12 3 views
1

데이빗 파워스 (David Powers)의 책 "PHP Solutions"를 통해 PHP를 배웠습니다. 기본 유효성 확인/오류 처리 및 입력 소거 기능이있는 문의 양식이 있습니다. 새로 고치지 않고 사용하고 싶습니다. 그 페이지.PHP 자체 제출 양식 및 유효성 검사가 포함 된 AJAX

XAMPP를 사용하여 로컬에서 테스트하고 있으며 PHP 양식 자체가 완벽하게 작동합니다. 오류 메시지가 올바르게 표시되고 양식이 성공적으로 제출되면 감사 페이지가 표시되고 양식이 전자 메일로 배달됩니다. 내 테스트 이메일 주소.

이제 AJAX에 오류 메시지를 제출하고 표시하려면 양식이 필요합니다. 이 작업을 수행하는 데 많은 게시물을 읽었지만 구현에 실패했습니다. jQuery $ .ajax 및 $ .post 메서드를 모두 시도했습니다 - 필드가 모두 채워지면 성공 메시지가 표시되지만 메시지는 보내지지 않습니다.

내 생각 엔 자바 스크립트와 PHP 배열은 다르게 구성되어 있지만이를 조정하는 방법을 모른다. 나는 PHP 처리 스크립트가 무엇을 얻고/보내고 있는지에 대해 확신하지 못한다. 페이지를 새로 고치지 않고 서버 측 유효성 검사를 위해 PHP 스크립트를 사용하여이 양식을 제출하려면 어떻게해야합니까?

단순화하기 위해 php, html 및 jQuery/AJAX 형식을 제외하고 내 페이지의 모든 것을 모두 제거하고 모든 파일을 같은 폴더에 넣었습니다.

희망적입니다. 제 4 개 파일 :

mySite = { 

    jsFormSubmission : function() { 
     $("#feedback").submit(function(event){ 
      event.preventDefault(); 
      var errorMsg = "<p class=\"errorBox\">Please fix the item(s) indicated.</p>"; 
      var successMsg = "<p class=\"messageBox\">Thanks for the submission, your message has been sent.</p>"; 

      var myObject = { 
       name : $("#name").val(), 
       email : $("#email").val(), 
       comments : $("#comments").val() 
      }; 

      var ajaxData = JSON.stringify(myObject); 

      $.ajax({ 
       type: 'POST', 
       url: 'form.php', 
       data: ajaxData, 
       success: function(data){ 
        $(".formResult").html(successMsg); 
       }, 
       error: function(http) { 
        $(".formResult").html(errorMsg); 
        alert(http.responseText); 
       } 
      }); 
     }); 
    } 

}; 

양식 (contact.php) :

<?php include("form.php"); ?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" > 
<head> 
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> 
    <script type="text/javascript" src=" mySite.js"></script> 
    <script type="text/javascript"> 
     $(document).ready(function() { 
      mySite.jsFormSubmission(); 
     }); 
    </script> 
</head> 

<body> 
    <div id="contact"> 

     <p class="formResult"></p> 

     <?php $errorForm = (($_POST && $suspect) || ($_POST && isset($errors['mailfail']))); 
       $errorTag = $missing || $errors; 
       if ($errorForm || $errorTag) { ?> 

     <p class="errorBox"> 
     <?php } ?> 
      <?php if ($errorForm) { ?> 
       Sorry, your message could not be sent. Please try again later. 
       <?php } elseif ($errorTag) { ?> 
       Please fix the item(s) indicated. 
      <?php } ?> 
     <?php if ($errorForm || $errorTag) { ?> 
     </p> 
     <?php } ?> 

     <form id="feedback" method="post" action=""> 

      <div class="tag"> 
       <label id="lblName" for="name">Name: 
       <?php if ($missing && in_array('name', $missing)) { ?> 
        <span style="color:red; font-weight:bold;">Please enter your name</span> 
       <?php } ?> 
       </label> 
       <input name="name" id="name" type="text" class="formbox" 
       <?php if ($missing || $errors) { 
        echo 'value="' . htmlentities($name, ENT_COMPAT, 'UTF-8') . '"'; 
       } ?>> 
      </div> 

      <div class="tag"> 
       <label id="lblEmail" for="email">Email: 
       <?php if ($missing && in_array('email', $missing)) { ?> 
        <span style="color:red; font-weight:bold;">Please enter your email address</span> 
       <?php } elseif (isset($errors['email'])) { ?> 
        <span style="color:red; font-weight:bold;">Invalid email address</span> 
       <?php } ?> 
       </label> 
       <input name="email" id="email" type="text" class="formbox" 
       <?php if ($missing || $errors) { 
        echo 'value="' . htmlentities($email, ENT_COMPAT, 'UTF-8') . '"'; 
       } ?>> 
      </div> 

      <div class="tag"> 
       <label id="lblComments" for="comments">Comments: 
       <?php if ($missing && in_array('comments', $missing)) { ?> 
        <span style="color:red; font-weight:bold;">Please enter your message</span> 
       <?php } ?> 
       </label> 
       <textarea name="comments" id="comments" cols="60" rows="8"><?php 
        if ($missing || $errors) { 
         echo htmlentities($comments, ENT_COMPAT, 'UTF-8'); 
        } ?></textarea> 
      </div> 

      <p> 
       <input name="send" id="send" type="submit" value="Send message"> 
      </p> 

     </form> 
    </div> 
    </body> 
</html> 

형태

mySite.js (JQuery와/AJAX 나는에 문제가 ...가 있어요)

<?php 
$name = ''; 
$email = ''; 
$comments = ''; 
$required = ''; 
$errors = array(); 
$missing = array(); 
// check if the form has been submitted 
if (isset($_POST['send'])) { 
    //email processing script 
    $to = '[email protected]'; 
    $subject = 'Website contact form'; 
    //list expected fields 
    $expected = array('name', 'email', 'comments'); 
    // set required fields 
    $required = array('name', 'email', 'comments'); 
    $headers = "From: Website Contact Test<[email protected]>\r\n"; 
    $headers .= 'Content-Type: text/plain; charset=utf-8'; 

    require('processmail.php'); 
    if ($mailSent) { 
     header("Location: thankYou.php#main"); 
     $messageConfirm = true; 
     exit; 
    } 
} 
?> 

processmail.php (검증 스크립트 - form.php에 포함) : .PHP는 (contact.php의 상단 포함)

<?php 

$suspect = false; 
$pattern = '/Content-Type:|Bcc:|Cc:/i'; 

// function to check for suspect phrases 
function isSuspect($val, $pattern, &$suspect) { 
    if (is_array($val)) { 
     foreach ($val as $item) { 
      isSuspect($item, $pattern, $suspect); 
     } 
    } else { 
     if (preg_match($pattern, $val)) { 
      $suspect = true; 
     } 
    } 
} 
isSuspect($_POST, $pattern, $suspect); 

if (!$suspect) { 
    foreach ($_POST as $key => $value) { 
     $temp = is_array($value) ? $value : trim($value); 
     if (empty($temp) && in_array($key, $required)) { 
      $missing[] = $key; 
     } elseif (in_array($key, $expected)) { 
      ${$key} = $temp; 
     } 
    } 
} 

// validate the user's email 
if (!$suspect && !empty($email)) { 
    $validemail = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL); 
    if ($validemail) { 
     $headers .= "\r\nReply-To: $validemail"; 
    } else { 
      $errors['email'] = true; 
    } 
} 

$mailSent = false; 

if (!$suspect && !$missing && !$errors) { 

    // initialize the $message variable 
    $message = ''; 
    foreach($expected as $item) { 
     if (isset(${$item}) && !empty(${$item})) { 
      $val = ${$item}; 
     } else { 
      $val = 'Not selected'; 
     } 
     if (is_array($val)) { 
      $val = implode(', ', $val); 
     } 
     $item = str_replace(array('_', '-'), ' ', $item); 
     $message .= ucfirst($item).": $val\r\n\r\n"; 
    } 

    $message = wordwrap($message, 70); 

    $mailSent = mail($to, $subject, $message, $headers); 
    if (!$mailSent) { 
     $errors['mailfail'] = true; 
    } 
} 
+0

'data :'$ ("# feedback"). serializeArray(); ','올바르지 않습니다. JS 코드를 직렬화 호출의 출력이 아닌 문자열로 제출합니다. 코드는 문자열이 아닌 다른 것으로 간주되지 않습니다.다른 모든 것을 던지면서 그 줄 위에 길을 잃어 버렸습니다. –

+0

아, 예, 실수로 삭제했습니다. '게시했을 때. 그 점을 지적 해 주셔서 감사합니다. – JMurky

+0

그리고 나는 데이터에 관한 당신의 요지를 보았습니다. 난 내 코드를 게시하려고 시도하고 단축하기 위해 사용했던 변수를 바꿨다. 아포스트로피 및 세미콜론을 제거하면 $ ("# feedback") serializeArray() 데이터를 읽으므로 여전히 아약스로 제출할 수 없습니다. – JMurky

답변

1

몇 가지 방법으로 PHP 측에서 오류를 표시 할 수 있습니다. 사용하여 jQuery를 오류 콜백하여 AJAX 호출에서

header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500); 

:

$.ajax({ 
    url: //url, 
    data: //data, 
    success: function (data) { //show success }, 
    error: function() { //display code here } 
}); 

당신은 또한에 오류를 반환 할 수 있습니다 당신은 내가 권하고 싶지 않다 예외를 던져, 또는 헤더를 사용할 수 있습니다 PHP 쪽에서 오는 오류 메시지의 본문 및 오류 콜백에서 본문을 제거합니다.

PHP :

header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500); 
echo 'Your error message'; 

자바 스크립트 :

error: function(http) { 
    // show http.responseText; 
} 

또한, 양식 제출, 객체에 데이터를 포장하고 직렬화. 따라서 :

var myObject = { 
    property1 : 'string', 
    property2 : [ 'array' ] 
}; 

var ajaxData = JSON.stringify(myObject); 
+0

자, myObject에서 각 필드에이 형식을 사용하고 ajaxData 변수를 다음과 같이 데이터 설정에 전달하려고합니다. $ .ajax ({data : ajaxData}) ;? 또는 ajaxData var도 직렬화해야합니까? 나는 전에 json과 일한 적이 없으며, 그것에 대해 조사 할 것이다. 도와 주셔서 감사합니다. 오늘 퇴근 후에 퇴근하려고합니다. – JMurky

+0

jQuery가이를 처리해야하므로 JSON.stringify를 사용하지 않고 원시 객체를 전달할 수 있습니다. PHP가 JSON 배열을 PHP 배열로 자동 입력하는지 기억이 안납니다. 나는 생각하지만, 나는 지금 당장 그것을 시험 할 입장이 아니다. –

+0

JavaScript에서 Object를 사용하면 변수를 수용 할 수있는 형식으로 마무리하는 데 많은 추가 작업이 필요하지 않습니다. 양식을 사용하는 경우 $ ('# myform'). serialize()를 사용하여 데이터를 쉽게 얻을 수 있지만 개체를 ​​사용하는 것이 더 좋습니다. –

관련 문제