2011-08-18 59 views
1

我很難將這個AJAX代碼實現到我的表單中,以便頁面不需要重新加載,但仍然會執行服務器端驗證。我是AJAX和PHP的新手,所以我正在處理一些表單模板,但是我一直在研究這個問題好幾個小時,但我無法弄清楚它爲什麼不起作用。任何幫助,將不勝感激。將表單數據發送到PHP服務器進行驗證的Ajax代碼

這裏是HTML代碼的一部分:

<div id="popupContact"> 
<form id="formElem" name="formElem" action="" method="post"> 
    <fieldset class="step"> 
      <legend>Personal Details</legend> 
      <p> 
       <label for="firstname">First Name</label><em>*</em> 
       <input id="firstname" name="firstname" /> 
      </p> 
      <p> 
       <label for="lastname">Last Name</label><em>*</em> 
       <input id="lastname" name="lastname" /> 
      </p> 
      <p>* fields are required</p> 
     </fieldset> 
     <fieldset class="step"> 
      <legend>Confirm</legend> 
     <p>Before you submit your information, please ensure that each step 
    below has this <img src="../img/global/checked.png" alt="Complete" > 
    above them. If there is a step that has this 
    <img src="../img/global/error.png" alt="Error" >, please click on that tab 
    and review the information to ensure it is correct and complete. Thank you.</p> 
    <p> 
       <label for="human">Please Type: "Something"</label><em>*</em> 
       <input id="human" name="human" /> 
      </p> 
      <p class="submit"> 
       <button id="registerButton" type="submit">Submit</button> 
      </p> 
     </fieldset> 
    </form> 
</div> 

這裏的JavaScript代碼:

$(function() { 
var form = $("#formElem"); 
var fname = $("#firstname"); 
var lname = $("#lastname"); 
var address = $("#streetaddress"); 
var city = $("#city"); 
var state = $("#state"); 
var phone = $('#phone'); 
var email = $('#email'); 
var insurance = $('#insurance'); 
var license = $('#license'); 
var human = $('#human'); 
$('#registerButton').bind('click',function(){ 
    if($('#formElem').data('errors')){ 
     alert('Please correct the errors in the Form'); 
     return false; 
    } 
    else { 
     var dataString = 'fname='+$('#firstname').val()+'&lname='+$('#lastname').val()+'&address='+$('#streetaddress'.val())+'&city='+$('#city')+'&state='+$('#state').val()+'&phone='+$('#phone').val()+'&email='+$('#email').val()+'&insurance='+$('#insurance').val()+'&license='+$('#license').val()+'&human='+$('#human').val(); 
     $.ajax({ 
     type: "POST", 
     url: "js/validation.php", 
     data: dataString, 
     async: false, 
     success: function() { 
       $('#popupContact').html("<div id='message'></div>"); 
       $('#message').html("<h2>Inquiry Submitted!</h2>") 
       .append("<p>We will be in touch soon.</p>") 
       .hide() 
       .fadeIn(1500, function() { 
       $('#message').append("<img id='checkmark' src='..img/global/check.png' />"); 
       }); 
     } 
    }); 
    return false; 
    } 
}); 

而這裏的PHP代碼:

<?php 
if(isset($_POST['email'])) { 
$email_to = "[email protected]"; 
$email_subject = "Inquiry"; 
function died($error) { 
    // your error code can go here 
    echo "We are very sorry, but there were error(s) found with the form you submitted. "; 
    echo "These errors appear below.<br /><br />"; 
    echo $error."<br /><br />"; 
    echo "Please go back and fix these errors.<br /><br />"; 
    die(); 
} 

// validation expected data exists 
if(!isset($_POST['firstname']) || 
    !isset($_POST['lastname']) || 
    !isset($_POST['email']) || 
    !isset($_POST['phone']) || 
    !isset($_POST['streetaddress']) || 
    !isset($_POST['city']) || 
    !isset($_POST['state']) || 
    !isset($_POST['insurance']) || 
    !isset($_POST['license']) || 
    !isset($_POST['human'])){ 
    died('We are sorry, but there appears to be a problem with the form you submitted.');  
} 

$firstname = $_POST['firstname']; // required 
$lastname = $_POST['lastname']; // required 
$emailfrom = $_POST['email']; // required 
$phone = $_POST['phone']; // required 
$address = $_POST['streetaddress']; //required 
$city = $_POST['city']; //required 
$state = $_POST['state']; //required 
$insurance = $_POST['insurance']; //required 
$license = $_POST['license']; //required 
$human = $_POST['human']; //required 

$error_message = ""; 
$email_exp = '/^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-][email protected][a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/'; 
if(!preg_match($email_exp,$emailfrom)) { 
$error_message .= 'The Email Address you entered does not appear to be valid.<br />'; 
} 

$email_message = "Form details below.\n\n"; 

function clean_string($string) { 
    $bad = array("content-type","bcc:","to:","cc:","href"); 
    return str_replace($bad,"",$string); 
} 

$email_message .= "First Name: ".clean_string($firstname)."\n"; 
$email_message .= "Last Name: ".clean_string($lastname)."\n"; 
$email_message .= "Email: ".clean_string($emailfrom)."\n"; 
$email_message .= "Telephone: ".clean_string($phone)."\n"; 
$email_message .= "Address: \n".clean_string($address)."\n"; 
$email_message .= "".clean_string($city).", "; 
$email_message .= "".clean_string($state)."\n"; 
$email_message .= "Have Insurance: ".clean_string($insurance)."\n"; 
$email_message .= "Have License: ".clean_string($license)."\n"; 


// create email headers 
$headers = 'From: '.$email_from."\r\n". 
'Reply-To: '.$email_from."\r\n" . 
'X-Mailer: PHP/' . phpversion(); 
@mail($email_to, $email_subject, $email_message, $headers); 
?> 

<!-- include your own success html here --> 

Thank you for contacting us. We will be in touch with you very soon. 

<?php 
}  
?> 

我省略了大部分的它的實際驗證代碼部分,所以我知道你看到的不完整。我不明白的是,如果沒有這個AJAX部分,表單驗證的工作方式就很好 - 客戶端和服務器端,但是當我添加AJAX時,某些東西沒有連接。感謝您的幫助提前。

編輯 有沒有人有我的代碼出錯的建議?

編輯 好了,所以如果我把js/validation.phpaction=""標籤的形式和禁用碼的AJAX部分,然後驗證工作得很好,但我轉發到一個網頁,只是空白確認碼。這在這個問題上有什麼亮點嗎?真的,任何幫助表示讚賞。我嘗試過使用評論中給出的提示,但由於某種原因沒有任何反應。它看起來像我的網頁刷新,但沒有確認信息,或任何東西。我完全失去了。

+0

這並不回答你的驗證問題,但我想指出,你可以使用$ .post(「test.php」,$(「#testform」)序列化整個表單。 ()); ..不需要獲取每個值並將它們作爲一個字符串粘在一起。您使用的是Apache錯誤日誌和Firefox錯誤控制檯,您是否使用 – Stephen

+0

?找出ajax錯誤是非常寶貴的。 –

+0

@Stephen - 所以在這種情況下,我可以將其重寫爲:'$ .post(「validation.php」,$('#contact_form')。serialize());'擺脫'var dataString = blahblahblah; '部分? – Michael

回答

4

你並不遙遠,但我認爲我會以稍微不積極的態度攻擊它。

  1. 從表單開始,我只是把它做成一個帶有ID的表單,然後將提交按鈕停放在表單標籤之外。爲什麼?因爲表單中的按鈕可能會產生一些不良效果(如提交給魔法黑洞)代碼少=開發人員開心。
  2. 我會點擊按鈕點擊處理程序。所以:

    $('#registerButton')。click(function(){ 在這裏做你的ajax });

  3. 我會在最初使用前端驗證時發現錯誤,因爲它可以節省服務器命中,從UI角度來看更令人愉快。它也更快......但不是,它不能完全依賴,因爲任何有能力的人都可以推翻它,但這是一個好的第一步。我個人最喜歡的是here

  4. 在點擊操作中,我會使用ajax(就像您在 示例中那樣)將表單提交到您的腳本進行驗證。 序列化的形式發送過來:

    $.ajax({ 
          type: "POST", 
          url: "js/validation.php", 
          data: $('#formElem').serialize(), 
          ... 
    

    我有腳本返回一個JSON字符串與結果的情況下 (真/假)和數據來支持這種情況下(如 成功的ID ,以及錯誤數組爲false)所以,你是 做與上面的ajax呼叫完全正確,但返回 數據 類型爲我的例子作爲json(而不是dataString),並添加一個var 成功後的parens(讓我們以returndata爲例)然後,在您的 成功回調中,返回的數據將作爲 returndata.field(變更字段等於在 JSON字符串變量名),如果它不工作,檢查輸出上 jsonlint.com

  5. 在Ajax調用的成功步驟4,設置2案件(如果別的)。如果你的結果案例是真實的,讓他們繼續,並表明你的用戶界面指示成功。如果結果案例爲false,則遍歷錯誤案例數組以通知用戶每個問題。

你快到了。如果這是您第一次使用jQuery AJAX,我真的很感動!

+0

這正是我需要的指導。感謝您花時間瀏覽我的代碼並寫下它。對此,我真的非常感激! – Michael

1

我知道你已經接受了一個答案,但我也想建議查看jQuery Validate插件 - http://bassistance.de/jquery-plugins/jquery-plugin-validation/ - 不需要真的重寫輪子。我個人使用這個插件,我使用jQuery進行任何類型的客戶端驗證。我也提到了這一點,因爲插件帶有一個本地的「遠程」驗證類型,您可以使用幾行簡單的代碼行進行任何類型的遠程驗證。我也在一些地方看過jQuery可能會在某個時候「正式」支持驗證插件,所以它不會早於以後開始使用它。只是一些思考的食物!

相關問題