如果值存在则显示模态,否则显示错误消息

问题描述 投票:0回答:1

切换不完全是术语但是,我想首先检查值是否存在,然后显示我的模态,如果不是模态必须不显示,只是PHP错误消息。

现在发生的是,如果值不存在,模态将显示,但当我刷新当前页面时,我的错误消息显示。这是我的Ajax与我的Jquery。

 $(function(){
  $(document).on('click', '.cScanBtn', function(e){
    e.preventDefault();
    var inputQr = $('#scanQr').val();
    //console.log(inputQr);
    $('#inputBarcode').val(inputQr);
    location.reload();

      $.ajax({
        type: 'POST',
        url: 'display_item.php',
        data: {
          inputQr:inputQr
        },
        success: function(result){
        //console.log(result);
        }
      });  
      $('#viewItem').modal('show');
  }); 
});

这是我的Ajax文件

<?php 

include 'includes/session.php';

$qr_code = $_POST['inputQr'];

$conn = $pdo->open();

    $checkQr = $conn->prepare("SELECT *, COUNT(*) AS checkrows FROM product WHERE qr_code=:qr_code");

    $checkQr->execute(['qr_code'=>$qr_code]);

    $qr = $checkQr->fetch();

    if($qr['checkrows'] <= 0){  

        $_SESSION['error'] = 'Barcode doesn\'t exist! Kindly review your input!';

    }   

$pdo->close();

?>
jquery ajax pdo
1个回答
0
投票

我想你必须改变你的逻辑,比如

 $(function(){
  $(document).on('click', '.cScanBtn', function(e){
    e.preventDefault();
    var inputQr = $('#scanQr').val();
    //console.log(inputQr);
    $('#inputBarcode').val(inputQr);
    //location.reload(); // not required.
      $.ajax({
        type: 'POST',
        url: 'display_item.php',
        dataType:'json', // <--- we will get json response
        data: {
          inputQr:inputQr
        },
        success: function(result){
            // get the json response, and if the error status then show message in alert
            (result.status == 'error' && alert(result.message))
             || $('#viewItem').modal('show'); // or just show the modal
        }
      });  
  }); 
});

现在,在PHP中更改你的代码,比如

<?php 
    include 'includes/session.php';
    $qr_code = $_POST['inputQr'];
    $conn = $pdo->open();
    $checkQr = $conn->prepare("SELECT *, COUNT(*) AS checkrows FROM product WHERE qr_code=:qr_code");
    $checkQr->execute(['qr_code'=>$qr_code]);
    $qr = $checkQr->fetch();
    $response = array('status'=>'success','message'=>'Barcode exists'); // be positive here
    if($qr['checkrows'] <= 0){
        $msg = 'Barcode doesn\'t exist! Kindly review your input!';
        $_SESSION['error'] = $msg;
        $response = array('status'=>'error','message'=>$msg);
    }
    $pdo->close();
    echo json_encode($response);
?>
© www.soinside.com 2019 - 2024. All rights reserved.