如何修复AJAX中未定义的POST索引?

时间:2018-10-22 02:47:23

标签: php jquery ajax

我在我的php文件中发送了一个ajax“ POST”。但是问题是POST的索引未定义。

这是我用ajax编写的示例代码。

$(".add-percentage").click(function(){

    var percentage_id = $(this).data('landing_id-percentage');

    $.ajax({
        url: 'ajax/readPercentage.php',
        type: 'POST',
        data: { percentage_id : percentage_id },
        success: function(data) {
          alert(data);
        },
        error: function(request, status, error){
          alert("Error!! "+error);
        }             
  });
});

我的php代码具有未定义的索引POST。

if(isset($_POST['percentage_id'])){

   $percentage_id = $_POST['percentage_id'];

   $query = mysqli_query($conn, "SELECT * FROM percentage WHERE percentage.percentage_id = '$percentage_id'");
}else{
  echo "Index is not properly set!";
}

我希望有人能帮助我。预先感谢。

2 个答案:

答案 0 :(得分:0)

if($_SERVER['REQUEST_METHOD']=="POST"){
   $data = file_get_contents('php://input');
   print_r($data); // for testing purpose.

   /*
   $query = mysqli_query($conn, "SELECT * FROM percentage WHERE percentage.percentage_id = $data[0]['pecentage_id']");
   */
}else{
  echo "Index is not properly set!";
}

答案 1 :(得分:0)

请将此代码用于Ajax

$(".add-percentage").click(function(){

    var percentage_id = $(this).data('landing_id-percentage');

    $.ajax({
        url: 'ajax/readPercentage.php',
        type: 'POST',
        dataType: 'json',
        data: { percentage_id : percentage_id },
        success: function(data) {
          alert(data.status);
        },
        error: function(request, status, error){
          alert("Error!! "+error);
        }             
  });
});


<?php
$result_array= array();
if(isset($_POST['percentage_id'])){

   $percentage_id = $_POST['percentage_id'];
   $select_query = "SELECT * FROM percentage WHERE percentage.percentage_id =".$percentage_id;

   $query = mysqli_query($conn,$select_query);
   $result_array['status'] = 'success';
   $result_array['success_msg'] = 'Data get successfully';
}else{
  //echo "Index is not properly set!";
  $result_array['status'] = 'failure';
  $result_array['error_msg'] = 'Index is not properly set!';
}
echo json_encode($result_array);
    die();
?>