首页 > 解决方案 > 如果值存在则显示模态,如果不存在则显示错误消息

问题描述

Toggle 不完全是术语,但是,我想先检查值是否存在,然后显示我的模态,如果不是,则不能显示模态,只是一个 PHP 错误消息。

现在发生的情况是,如果该值不存在,则模式将显示,但是当我刷新当前页面时,我的错误消息会显示。这是我的 Jquery 和我的 Ajax。

 $(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();

?>

标签: jqueryajaxpdo

解决方案


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

 $(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);
?>

推荐阅读