【发布时间】:2021-11-20 00:57:54
【问题描述】:
我正在使用SweetAlert 进行确认,我无法从我的 php 获取返回数据到 ajax
这就是我正在做的事情
我的后端 php
//Add A voucher
public function AddVoucher ($voucher_name, $quantity, $discount)
{
try
{
$stmt2 = $this->db->prepare("SELECT * FROM vouchers WHERE voucher_name=:voucher_name");
$stmt2->bindParam(":voucher_name", $voucher_name,PDO::PARAM_STR);
$stmt2->execute();
$stmt2->fetchAll(PDO::FETCH_ASSOC);
if($stmt2->rowCount())
{
return "Failed";
}
else
{
$discount /= 100;
//name doesn't exist so proceed to registration
$stmt = $this->db->prepare("INSERT INTO vouchers (voucher_name,quantity,discount)
VALUES(:voucher_name, :quantity, :discount)");
$stmt->bindParam(":voucher_name", $voucher_name,PDO::PARAM_STR);
$stmt->bindParam(":quantity", $quantity,PDO::PARAM_STR);
$stmt->bindParam(":discount", $discount,PDO::PARAM_INT);
$stmt->execute();
return $stmt;
}
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
我的模型 php
<?php
require_once '../database/database.php';
$voucher_name = $_POST['voucher_name'];
$quantity = $_POST['quantity'];
$discount = $_POST['discount'];
$result = $user->AddVoucher($voucher_name,$quantity,$discount);
if($result == "Failed"):
return false;
else:
return true;
endif
?>
现在是我的 ajax 所在的前端
function SwalConfirm()
{
Swal.fire({
title: 'Are you sure?',
text: "You will an a voucher . Do you wish to proceed",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, Proceed',
cancelButtonText: 'No, cancel!',
confirmButtonClass: 'btn bg-gradient-primary w-30',
cancelButtonClass: 'btn bg-gradient-secondary w-30',
buttonsStyling: false,
preConfirm: function()
{
return new Promise(function(resolve){
$.ajax({
url: '../model/voucher_add.php',
type: 'POST',
data:
{
voucher_name: $('#a_voucher_name').val(),
quantity: $('#a_quantity').val(),
discount: $('#a_discount').val()
},
success: function(data)
{
if(!data)
{
Swal.fire('Opps!', 'Voucher Name Already Exists. Please Edit the current voucher instead','warning').then(function(){
location.reload();
});
}
else
{
Swal.fire('Success!', 'You have successfully added a voucher.','success').then(function(){
location.reload();
});
}
}
})
// .done(function(response)
// {
// Swal.fire('Opps!', 'Voucher Name Already Exists. Please Edit the current voucher instead','warning').then(function(){
// location.reload();
// });
// })
.fail(function(){
Swal.fire('Oppss!', 'There was something wrong declining this request.','success')
})
});
}
});
}
我在这里尝试做的是,如果当前凭证已经存在,则不要继续使用sweetalert 而不是成功消息来显示错误
【问题讨论】:
-
使用
return不会做任何事情,你需要回显1或0,或者用json响应并设置ajax调用以使用dataType: 'json'处理它 -
还要注意,
echo $ex->getMessage();会导致它中断或看起来像 true,该函数不应捕获然后回显并返回 null,而应始终返回 true 或 false,或者新凭证或空数组。调用时可以捕获抛出的异常。 -
np,不知道,我看不出你的问题有什么问题
-
你能写下你的答案吗?现在它实际上已经被
echo '0';解决了
标签: php ajax sweetalert sweetalert2