jquery - 如果值存在则显示模态,如果不存在则显示错误消息
问题描述
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();
?>
解决方案
我认为你必须改变你的逻辑,比如,
$(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);
?>
推荐阅读
- scikit-learn - “余弦”度量在 sklearn 的聚类算法中如何工作?
- microsoft-graph-api - 在 ms-graph 'create' 订阅响应中 applicationId 是什么意思
- linux - 如何在没有绝对地址的 Linux 中查找文件?
- c++ - How to delete a string based on spaces
- javascript - 结合两个选择来查询数据库
- css - flexbox对齐子容器项目?
- google-app-maker - 下拉菜单无法保存到数据源
- python - Python 私有实例变量行为
- python - 如何根据数据类型识别列并在pyspark中转换它们?
- python - 为什么我会收到此 KeyError?