2016-02-11 66 views
1

如果我保留電子郵件和/或密碼字段爲空並嘗試提交表單,它會向我提供客戶端錯誤消息以填充輸入框中的所需數據。如何使用AJAX顯示不同的成功/錯誤PHP消息

一旦我在表單頁面上輸入正確的電子郵件和密碼後提交表格,它會在數據庫表格中插入數據並給我成功的信息。

但是,如果我在表單頁面上輸入不正確的電子郵件和/或祕密代碼後提交表單,由於服務器端驗證腳本我已經寫入,它不會在數據庫表中插入數據,但仍然給我成功消息而不是給出特定不正確的電子郵件和/或密碼的錯誤消息。

我需要做些什麼來顯示特定的錯誤消息,我從服務器端頁面獲取不正確的數據?

客戶端頁面(contact.js)

$(function() { 
    $("#MyFormName input).jqBootstrapValidation({ 
    preventSubmit: true, 
    submitError: function($form, event, errors) { 
     // something to have when submit produces an error ? 
     // Not decided if I need it yet 
    }, 
    submitSuccess: function($form, event) { 
     event.preventDefault(); // prevent default submit behaviour 
     // get values from FORM 
     var emailid = $("input#emailid").val(); 
     var secretcode = $("input#secretcode").val(); 

     $.ajax({ 
      url: "./contact_p.php", 
      type: "POST", 
      data: { 
       emailid: emailid, 
       secretcode: secretcode 
      }, 
      cache: false, 
      success: function() { 
       // Success message 
       $('#success').html("<div class='alert alert-success'>"); 
       $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;") 
        .append("</button>"); 
       $('#success > .alert-success') 
        .append("<strong>Success Message will come here.</strong>"); 
       $('#success > .alert-success') 
        .append('</div>'); 

       //clear all fields 
       $('#FormPRegister').trigger("reset"); 
      }, 
      error: function() { 
       // Fail message 
       $('#success').html("<div class='alert alert-danger'>"); 
       $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;") 
        .append("</button>"); 
       $('#success > .alert-danger').append("<strong>Sorry " + " Error Message will come here!"); 
       $('#success > .alert-danger').append('</div>'); 
       //clear all fields 
       $('#FormPRegister').trigger("reset"); 
      }, 
     }) 
    }, 
    filter: function() { 
     return $(this).is(":visible"); 
    }, 
}); 

$("a[data-toggle=\"tab\"]").click(function(e) { 
    e.preventDefault(); 
    $(this).tab("show"); 
}); 
}); 

/*When clicking on Full hide fail/success boxes */ 
$('#r_name').focus(function() { 
    $('#success').html(''); 
}); 

服務器端頁面(contact_p.php)

if(empty($str_emailid)) 
{ 
    echo "No Email ID entered!"; 
    return false; 
} 
if(empty($str_secretcode) || $_SESSION['image_secret_code'] != $str_secretcode) 
{ 
    echo "Invalid Secret Code!"; 
    return false; 
} 

$str_insert = "INSERT INTO t_contact (emailid,idate,ipaddress) VALUES('".$str_emailid."','".date("Y-m-d H:i:s")."','".$_SERVER['REMOTE_ADDR']."')"; 
RunQuery($str_insert); 

return true;    

回答

0

在這裏,我張貼我的整個工作腳本在PHP,AJAX,JSON。我相信其他人會爲聯繫表單頁面提供不同類型的工作腳本,但這對我來說工作正常。

我從這裏得到了許多人的幫助,使它工作。所以這都是他們的努力,我真的很感謝他們的幫助。所以我認爲我應該在這裏發佈整個劇本,以便對我這樣的其他人也有用。

備註#1:alert(data);將有助於警報,狀態和消息

注#2 JSON陣列響應:我沒有使用任何現成的腳本captacha

contact.php

<form name="FormPRegister" id="FormPRegister" novalidate> 
. 
. 
other form fields will come here 
. 
. 
<div class="control-group form-group"> 
    <div class="controls"> 
     <label>Email Address:</label> 
     <input type="email" class="form-control" id="r_email" name="r_email" required data-validation-required-message="Please enter your email address."> 
    </div> 
</div> 
<div class="control-group form-group"> 
    <div class="controls"> 
     <label>Secret Code:</label> 
     <div class="input-group"> 
     <input type="text" class="form-control" id="r_secretcode" name="r_secretcode" required data-validation-required-message="Please enter secret code from given image."><span class="input-group-addon input-group-addon-no-padding"><img src="./includes/get_unique_image.php" border="0"></span> 
    </div> 
</div> 
</div> 
<div id="success"></div> 
<!-- For success/fail messages --> 
<button type="submit" class="btn btn-primary" tabindex="9">Send Message</button> 
</form> 

contact.js

$.ajax({ 
    url: "./contact_p.php", 
    type: "POST", 
    data: { 
    emailid: emailid, 
    secretcode: secretcode 
}, 
cache: false, 

success: function(data) 
{ 
//alert(data); 
var $responseText=JSON.parse(data); 
if($responseText.staus == 'SUC') 
{ 
    // Success message 
    $('#success').html("<div class='alert alert-success'>"); 
    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;") 
    .append("</button>"); 
    $('#success > .alert-success').append("<strong> " + $responseText.message + " </strong>"); 
    $('#success > .alert-success').append('</div>'); 

    //clear all fields 
    $('#FormPRegister').trigger("reset"); 
} 

else if($responseText.status == 'ERR') 
{ 
    // Fail message 
    $('#success').html("<div class='alert alert-danger'>"); 
    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;") 
    .append("</button>"); 
    $('#success > .alert-danger').append("<strong> " + $responseText.message + " "); 
    $('#success > .alert-danger').append('</div>'); 
} 
}, 
}) 

contact_p.php

. 
. 
other script will come here as per requirements 
. 
. 
if(empty($_POST["r_email"])) 
{ 
    $response['status']='ERR'; 
    $response['message']= "Invalid Email ID!"; 
    echo json_encode($response); 
    return; 
} 
if(empty($_POST["r_secretcode"]) || $_SESSION['image_secret_code'] != $_POST["r_secretcode"]) 
{ 
    $response['status']='ERR'; 
    $response['message']= "Invalid Secrete Code!"; 
    echo json_encode($response); 
    return; 
} 
. 
. 
other script will come here as per requirements 
. 
. 
if(Invalid data then do this) 
{ 
    $response['status']='ERR'; 
    $response['message']= "Invalid Secrete Code!"; 
    echo json_encode($response); 
    return; 
} 
if(Valid data then do this) 
{ 
    $response['status']='SUC'; 
    $response['message']= "Inquiry submitted successfully"; 
    echo json_encode($response); 
    return; 
} 
. 
. 
other script will come here as per requirements 
. 
. 
1

這是不是你的「服務器端頁面「既然你給了回報,這是一種方法。根據您的設置,您應該可以在JSON對象中返回信息,以便JavaScript可以輕鬆訪問您的信息,也許可以提供對象的名稱。

{錯誤:[郵件:「無電子郵件進入」]}

等。雖然這樣做,如果你遵循的標準,你應該返回一個400頭以及(雲在代碼的任何地方,當事情錯誤)。

header('HTTP/1.1 400 Bad-Request', true, 400); 

這應該會導致錯誤功能被觸發。

避免只是迴應字符串,allthough它應該適用於你的情況,當你也設置此標題。

你應該也可以在你的問題中標記jQuery,因爲這是與jQuery相關的。

編輯:

忘了一兩件事,實際上使用來自服務器的響應的執行以下操作:

是這樣的:

error: function() { 

應該

error: function(response, status, xhr) { 

欲瞭解更多信息只看jQuery文檔,成功的消息也是如此。你可以用同樣的方式檢查那裏的迴應。

如果您只是響應一個字符串,則響應應該包含錯誤消息對象。例如,Json對象將允許返回更多信息。

http://api.jquery.com/jquery.ajax/

+0

Ty爲您的答覆。是否有任何教程或指導或幫助我可以學習和實施你在答案中提出的建議。這對我非常有幫助。 –

+0

不確定,但我想你可以開始使用基本的jQuery和PHP教程,谷歌應該幫助你找到一些。 這需要練習我猜。 –

-1

那怎麼Ajax的工作原理。你的php代碼很好,這就是爲什麼你的ajax執行success函數。 error只會在您的請求失敗時執行。

在這種情況下,您需要在success函數中處理您的錯誤消息。

試試這個:

PHP代碼:

if(empty($str_emailid)) 
{ 
    $arr = array("msg"=>"No Email ID entered!","status"=>400); 

} else if(empty($str_secretcode) || $_SESSION['image_secret_code'] != $str_secretcode) 
{ 

    $arr = array("msg"=>"Invalid Secret Code!","status"=>400); 
} else { 

$str_insert = "INSERT INTO t_contact (emailid,idate,ipaddress) VALUES('".$str_emailid."','".date("Y-m-d H:i:s")."','".$_SERVER['REMOTE_ADDR']."')"; 
RunQuery($str_insert); 

$arr = array("msg"=>"Success","status"=>200); 
} 

    echo json_encode($arr); 
    exit; 

而在阿賈克斯你的成功的功能:

success: function(res) { 
       if(res.status == 400) { 
        //error message 
       } else { 
        //success message 
       } 
      } 
+1

狀態400是否觸發錯誤?我不再使用jquery,但我認爲它會。 –

+0

不,不在我的情況。我只是通過狀態來檢查它是錯誤消息還是成功消息。我沒有發送HTTP響應代碼。 –

+0

啊沒有看你的PHP。那也是可以的。 –

0

我認爲你應該在PHP中使用JSON格式進行有效像下面 -

if(empty($str_emailid)) 
{ 
    $response['status']='ERR'; 
    $response['message']= "No Email ID entered!"; 
    return json_encode($response); 
} 
if(empty($str_secretcode) || $_SESSION['image_secret_code'] !=  $str_secretcode) 
{ 
    $response['status']='ERR'; 
    $response['message']= "Invalid Secrete Code!"; 
    return json_encode($response); 
} 
$str_insert = "INSERT INTO t_contact (emailid,idate,ipaddress) VALUES('".$str_emailid."','".date("Y-m-d H:i:s")."','".$_SERVER['REMOTE_ADDR']."')"; 
RunQuery($str_insert); 
$response['status']='OK'; 
$response['message']='Inserted successfully'; 
return json_encode($response); 

在jquery方面的成功

success: function(data) { 
      // Success message 
      $responsetext=JSON.parse(data); 
      if($responseText.status=='OK') 
      { 
       $('#success').html("<div class='alert alert-success'>"); 
       $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;") 
       .append("</button>"); 
       $('#success > .alert-success') 
       .append("<strong>Success Message will come here.</strong>"); 
       $('#success > .alert-success') 
       .append('</div>'); 

       //clear all fields 
       $('#FormPRegister').trigger("reset"); 
      } 
      else if($responseText.status=='ERR') 
      { 
       // do your stuff with your error 
      } 

     }, 

希望這對你有幫助嗎?

+0

Ty代表您的詳細解答。但是現在它不允許我在進行修改後提交表單。 –

+0

仔細看,檢查你的拼寫...我使用相同的格式,因爲1年....在jquery只是複製成功的功能和粘貼在你的代碼,,,看看控制檯,以確保語法錯誤....與出這個你怎麼可以投票嗯......我只是編輯我的代碼爲你的容易....並回應我 –

+0

對不起,但我還沒有投票你的答案...我會檢查你的語法和其他的東西建議。 –