当按下确认按钮时,我能够发送数据。
但是,当按下取消按钮时,sweetalert2 显示已成功插入数据。
后端显示为空字符串。(在数据库表中)
如何在我按下取消按钮时进行验证,而不是将数据发送到后端。
Javascript 函数
function inputPass(complaintID) { // complaint id pass is ok.
swal({
text: 'Input comment message',
input: 'textarea',
showCancelButton: true,
}).then(function(sample_text) {
console.log(sample_text);
if(sample_text === '') { // problem is here.
swal({
type: 'warning',
html: 'cannot proceed without input'
});
} else {
console.log(sample_text);
$.ajax({
type: "POST",
url: "../ajax/ajax_active_deact.php?type=complaint_answered",
data: {complaintID: complaintID, sampleText: sample_text}
}).done(function (res) {
if(!res) {
swal({
type: 'error',
html: 'insert the valid text'
});
} else {
swal({
title: 'done',
text: 'all right',
type: 'success',
allowOutsideClick: false,
confirmButtonText: 'Ok'
});
}
});
}
});
}
php ajax代码
function complaint_answered() {
include_once('../backend/ConsumerComplaint.php');
$con_complaint = new ConsumerComplaint();
$res = $con_complaint>mark_as_answered($_POST['complaintID'],$_POST['sampleText']);
echo $res;
}
这是我的类函数
function mark_as_answered($id, $comment) {
//var_dump($comment);
$val = $comment['value']; // $comment is a associative array, with the key of 'value'
$sql = "UPDATE c_consumer_complaint SET `status` = 'answered', `update` = '$val'
WHERE complaint_id = '$id' ";
$res = $this->conn->query($sql);
return $res;
}
我是开发新手,不知道如何解决这个问题。 请任何人都可以告诉我我在这里做错了什么。 谢谢!
最佳答案
只有当用户点击 Ok 时,您才会得到 result.value
,这样您就可以检查是否有一个值,如果它为空,则显示您的错误消息。如果没有值,则什么也不会发生。
片段:
swal({
text: 'Input comment message',
input: 'textarea',
showCancelButton: true,
}).then(function(result) {
if(result.value) {
$.ajax({
type: "POST",
url: "../ajax/ajax_active_deact.php?type=complaint_answered",
data: {complaintID: complaintID, sampleText: result.value}
}).done(function (res) {
if(!res) {
swal({
type: 'error',
html: 'insert the valid text'
});
} else {
swal({
title: 'done',
text: 'all right',
type: 'success',
allowOutsideClick: false,
confirmButtonText: 'Ok'
});
}
});
} else if (result.value === "") {
swal({
type: 'warning',
html: 'cannot proceed without input'
});
}
});
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@7.28.7/dist/sweetalert2.all.min.js"></script>
你的类(class):
在您的 php ajax 代码 中,您传递的不是数组而是字符串 $comment['value ']
将不包含文本。
function mark_as_answered($id, $comment) {
//var_dump($comment);
$val = $comment;
$sql = "UPDATE c_consumer_complaint SET `status` = 'answered', `update` = '$val'
WHERE complaint_id = '$id' ";
$res = $this->conn->query($sql);
return $res;
}
PS:请自学SQL-Injection因此人们无法将有害代码注入(inject)您的 SQL 查询。
关于javascript - 即使在 sweetalert2 中按下取消按钮,数据也会提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52894958/