简体   繁体   English

PHP的AJAX输出错误代码

[英]AJAX output error codes from PHP

After much struggling and reading online I still cannot find an answer for this question. 经过很多努力和在线阅读后,我仍然找不到这个问题的答案。 In my application the form gets sent via AJAX then in PHP it is validated and added to the database. 在我的应用程序中,表单是通过AJAX发送的,然后在PHP中被验证并添加到数据库中。 However, I can send a success message but I do not know how to send a friendly error message back to the user. 但是,我可以发送成功消息,但不知道如何将友好的错误消息发送回用户。

Below is my JS: 下面是我的JS:

$(document).ready(function(){
  var form = $('form');
  var submit = $('#submit');
  form.on('submit', function(e) {
      e.preventDefault();
      $.ajax({
          url: 'ajax_comment.php',
          type: 'POST',
          cache: false,
          data: form.serialize(),
          beforeSend: function(){
              submit.val('Posting...').attr('disabled', 'disabled');
          },
          success: function(data){
              var item = $(data).hide().fadeIn(800);
              $('.new-comment').append(item);

              form.trigger('reset');
              submit.val('Submit Comment').removeAttr('disabled');
          },
          error: function(e){
              alert(e);
          }
      });
  });
});

I have little experience in AJAX so please be simple with me! 我对AJAX的经验很少,所以请保持简单! The error messages will be along the lines of 'Username does not exist' etc so I don't think I could do this with client side validation. 错误消息将沿着“用户名不存在”等行显示,因此我认为我无法通过客户端验证来做到这一点。 Thanks in advance! 提前致谢!


EDIT: Below is my PHP code that I am using. 编辑:以下是我正在使用的PHP代码。

    <?php
// Include files
include 'config.php';

// Variables
$order_id = $_POST['order_id'];  
$comment  = $_POST['comment']; 
$reviewed = 1;
$date     = date('dS F Y');

// Find order ID match 
$stmt = $con->prepare("SELECT order_id FROM transactions WHERE order_id = ?");
$stmt->bind_param('i', $order_id);
$stmt->execute();
$stmt->store_result();
$no_id_match = $stmt->num_rows; 
$stmt->close(); 

// Check if review has already been submitted 
$stmt = $con->prepare("SELECT order_id FROM transactions WHERE order_id = ? AND review = 1");
$stmt->bind_param('i', $order_id);
$stmt->execute();
$stmt->store_result();
$num_rows_reviewed = $stmt->num_rows; 
$stmt->close(); 

if(empty($order_id) === true || empty($comment) === true) {
    exit();
} else if($num_rows_reviewed> 0) {
    exit();
} elseif($no_id_match == 0) {
    exit();
} elseif(strlen($comment) > 499) {
    exit();
} else {
    //Insert review into DB
    $stmt = $con->prepare("INSERT INTO reviews (order_id, comment, date) VALUES (?, ?, ?)");
    $stmt->bind_param('iss', $order_id, $comment, $date);
    $stmt->execute(); 
    $stmt->close();

    // Update transactions to show review added
    $stmt = $con->prepare("UPDATE transactions SET review = ? WHERE order_id = ?");
    $stmt->bind_param('ii', $reviewed, $order_id);
    $stmt->execute(); 
    $stmt->close();

    // Get name from order ID
    $stmt = $con->prepare("SELECT first_name, last_name FROM transactions WHERE order_id = ?");
    $stmt->bind_param('i', $order_id);
    $stmt->execute(); 
    $stmt->bind_result($first_name, $last_name);
    $stmt->fetch();
    $stmt->close();
    $name = $first_name. ' '. mb_substr($last_name, 0, 1);

    // Output review live to page ?>
    <div class="comment-item">
      <div class="comment-post">
        <h3><?php echo $name; ?>: <span><?php echo $date; ?></span></h3>
        <p><?php echo $comment; ?></p>
      </div>
    </div><?php 
}?>

At the moment the exit() variables are where I would like to validate the script. 目前, exit()变量是我要验证脚本的位置。 However since I do not know how to do this right now I am just exiting the script. 但是,由于我现在不知道如何执行此操作,因此我只是退出脚本。

You can send errors from backend with the HTTP way. 您可以使用HTTP方式从后端发送错误。

Send a PHP array encoded in json if all works fine. 如果一切正常,请发送以json编码的PHP数组。

$result = [];
$result['error'] = false;
$result['code'] = "OK"; //better with constant
$result['msg'] = "";
echo json_encode($result);

And like this if something didn't work. 如果无法解决问题,请像这样。

header('HTTP/1.1 500 Internal Server Error');
$result = [];
$result['error'] = false;
$result['code'] = "DB_UPDATE_ERROR"; //better with constant
$result['msg'] = "Impossible save bla, bla, bla";
echo json_encode($result);

I believe the solution is to add a success/error code (of your own) in very start of your PHP return. 我相信解决方案是在PHP返回开始时添加成功/错误代码(自己的)。

For instance if data (in success clause of ajax) function looks like "Incorrect Login Credentials", (which is coming from PHP of course), you should instead send "200Incorrect Login Information" OR "100Success Login" from PHP. 例如,如果数据(在ajax的成功子句中)功能看起来像“不正确的登录凭据”(当然来自PHP),则应该从PHP发送“ 200Incorrect Login Information”或“ 100Success Login”。

as you can see with 200 I mean PHP says there was an error / authentication or validation failure and with 100 I mean to tell AJAX that everything was accepted from PHP end. 如您看到的200,我的意思是PHP表示存在错误/身份验证或验证失败,而100的意思是告诉AJAX,PHP端接受了所有内容。

then you can do this in your jquery: 那么您可以在您的jquery中执行此操作:

var data_code = data.substring(0,3);
var return_message = data.substring(3); // this is return message without code

if(data_code == 100) { 
 //its a success
  document.location.replace("success.html");
} else if(data_code == 200) {
 //its a fail
  alert("Error: " + return_message);
}

EDIT: 编辑:

if(empty($order_id) === true || empty($comment) === true) {
    echo "200comment or order id is empty";
    exit();
} else if($num_rows_reviewed> 0) {
    echo "200";
    exit();
} elseif($no_id_match == 0) {
    echo "200";
    exit();
} elseif(strlen($comment) > 499) {
   echo "200 comment cannot be bigger then 499";
    exit();
} else {
   echo"100"; // all is good

please note that this method works just as expected but its a little tricky, I use it as well where I dont want to use json (as answered by other user). 请注意,此方法可以按预期工作,但有点棘手,我在不想使用json的地方也使用它(由其他用户回答)。


EDIT 编辑

success: function(data){
    var data_code = data.substring(0,3);
    var return_message = data.substring(3); // this is return message without code

    if(data_code == 100) { 
      var item = $(return_message).hide().fadeIn(800);
      $('.new-comment').append(item);

       form.trigger('reset');
       submit.val('Submit Comment').removeAttr('disabled');
    } else if(data_code == 200) {
     //its a fail
      alert("Error: " + return_message);
    }
},

I would recommend to use JSON as the response format. 我建议使用JSON作为响应格式。 So you can send an error message in an extra response key. 因此,您可以在额外的响应密钥中发送错误消息。 Example

{
   data: "<div>...</div>",
   error: "username does not exist"
}

In your response function you can use the returned keys for accessing the different data. 在响应功能中,您可以使用返回的键来访问不同的数据。

      success: function(returnedData){
          $('.new-comment').append(returnedData.data);
          if (returnedData.error) $('.error').append(returnedData.error);
      },

Be sure to set the dataType of the ajax request to "json". 确保将ajax请求的dataType设置为“ json”。

$(document).ready(function(){
var form = $('form');
var submit = $('#submit');
form.on('submit', function(e) {
e.preventDefault();
$.ajax({
      url: 'ajax_comment.php',
      type: 'POST',
      cache: false,
      data: form.serialize(),
      dataType:'json',
      beforeSend: function(){
          submit.val('Posting...').attr('disabled', 'disabled');
      },
      success: function(data){

          if(data.status) {
          var item = $(data).hide().fadeIn(800);
          $('.new-comment').append(item);

          form.trigger('reset');
          submit.val('Submit Comment').removeAttr('disabled');
          } else {
             alert(data.message);
             for(var value in data.fields) {
                alert(data.fields[value]); // can do error placement as well
             }
          }
      },
      error: function(e){
          alert(e);
      }
});
});
});

at ajax_comment.php file Just write code as a example your rest of code if error 在ajax_comment.php文件中,只需编写代码作为示例,如果出现错误,其余代码

$response['status'] = false;
$response['fields']['username'] = 'Not valid';  // fields name should be same like your 
$response['message'] = 'There are some error with given input, please correct'; 

form field name so error placement would be easy 表单字段名称,因此容易放置错误

if not any error 如果没有任何错误

$response['status'] = true;
$response['message'] = 'Successfully Submitted'; 

echo json_encode($response);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM