2013-02-12 17 views
1

我一直在通過David Powers的書「PHP Solutions」學習PHP,它有一個聯繫表單,包含基本驗證/錯誤處理和輸入消毒,我希望在不刷新的情況下使用這一頁。AJAX與PHP自我提交表單和驗證

我在XAMPP本地測試這個,並且使用php表單本身完美地工作:錯誤信息正確顯示,並且如果表單成功提交,將顯示一個感謝頁面並將表單作爲電子郵件發送給我的測試郵件地址。

現在我需要通過AJAX提交併顯示錯誤消息。我已經閱讀了很多關於完成這個任務的帖子,但是我在實現這個過程中沒有成功。我已經嘗試了jQuery $ .ajax和$ .post方法 - 如果字段全部填滿,則顯示成功消息,但不發送消息。

我的猜測是,JavaScript和PHP數組結構不同,但不知道如何協調這一點。我什至不知道什麼是PHP處理腳本獲取/發送,如果有的話。如何在不刷新頁面的情況下提交此表單,但是仍然使用php腳本進行服務器端驗證?

爲了簡化,我從我的頁面中刪除了所有其他內容(並將所有文件放在同一文件夾中),除了表單:php,html和我無法弄清楚的jQuery/AJAX。

希望這是有道理的。我的4個文件:

mySite.js(jQuery的/ AJAX我遇到的麻煩...):

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> 

形式.PHP(包括在contact.php的頂部):

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

$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代碼作爲字符串提交,而不是序列化調用的輸出 - 從未將代碼視爲字符串以外的任何其他代碼。你在這條線上面還有一個流浪的'''''''''''''''''''' – 2013-02-12 15:34:38

+0

嗯,是的,我不小心刪除了'當我發佈這個。感謝您指出了這一點。 – JMurky 2013-02-12 18:45:46

+0

我看到你對數據的觀點:''是一個字符串。我替換了我用來嘗試縮短我的代碼張貼的變量。如果我刪除撇號和分號,所以它讀取數據:$(「#feedback」)。serializeArray(),我仍然無法使用ajax提交。 – JMurky 2013-02-13 06:47:52

回答

1

有幾種方法可以讓您從PHP端顯示錯誤。您可以拋出一個異常,我不會推薦,或使用一個標題:

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

在你的AJAX調用,使用jQuery的錯誤回調:

$.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'; 

的JavaScript:

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 2013-02-12 18:58:27

+0

jQuery應該爲你做,所以你可以傳入對象原始(不使用JSON.stringify)。我不記得PHP是否會自動將JSON數組作爲PHP數組輸入。我認爲它確實存在,但我現在無法對此進行測試。 – 2013-02-12 20:24:34

+0

在JavaScript中使用對象消除了很多額外的工作,可以將變量轉換爲可接受的格式。如果你使用的是表單,你也可以使用$('#myform')。serialize()來獲取數據,但我覺得使用對象更好。 – 2013-02-12 20:29:38