Показать модальный, если значение существует, и показать сообщение об ошибке, если нет - PullRequest
0 голосов
/ 13 сентября 2018

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

?>

1 Ответ

0 голосов
/ 13 сентября 2018

Я думаю, что вы должны изменить свою логику, как,

 $(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);
?>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...