如果成功声明ajax

时间:2018-12-07 12:54:49

标签: php jquery mysql ajax

我无法在ajax成功函数中实现if语句。

<?php  
  include('../Config/config.php');
  $myquery = "SELECT * FROM voters WHERE Precinct = '".$_POST['precinct']."'";
  $execute = mysqli_query($mysqli, $myquery);
  if (mysqli_num_rows($execute) >= 1)
  {
    echo "Precinct is full.\n Recheck precinct number.";
  }
?>
function checkerprecinct() {
  var precinct = $("#precinct").val();
  $.ajax({
    type: "POST",
    url: "precinctchecker.php",
    data: "precinct=" + precinct,
    success: function(data) {
      console.log(data);
      if (data === "") {
        alert("Data is empty!");
      } else {
        alert(data);
      }
    }
  });
}

我想以此作为验证。
如果发送的数据包含来自数据库的相似数据,我想提醒用户。

1 个答案:

答案 0 :(得分:-2)

尝试此代码

更改您的代码

PHP代码:

$data = array();
if (mysqli_num_rows($execute) >= 1)
{
    $data= array('code'=>100,'message'=>"Precinct is full.\n Recheck precinct number.");
    //echo "Precinct is full.\n Recheck precinct number.";
}else{
    $data= array('code'=>101,'message'=>"Data is empty!");
}

echo json_encode($data);
exit;

ajax代码:

var data = JSON.parse(data);
if (data['code'] == 100) {
    alert(data['message']);
}