SweetAlerts Ajax With PHP



所以目前我正在尝试弹出一个SweetAlert,让您输入访问网站的密钥。我想设置它,这样你就可以输入密钥,它在一个单独的PHP页面上运行AJAX请求,然后如果该密钥存在,就会返回true或false。我确实尝试过使用SweetAlerts示例,但它不断出错。

JavaScript:

function SignUp() {
swal({
text: 'Enter Your 8-Digit Beta Key',
content: "input",
button: {
text: "Submit",
closeModal: false,
},
})
.then(key => {
if (!key) throw null;
return fetch(`beta/database.php?mode=key&key=${key}`);
})
.then(results => {
return results.json();
})
.then(json => {
const key = json.results[0];
const result = key.tf;
if (result == "false") {
return swal("Key Invalid", "Key Is Invalid, Have You Already Registered?", "error");
}
swal("Key Valid", "Redirecting", "success");
})
.catch(err => {
if (err) {
console.log(err);
swal("Error", "Something Went Wrong, Try Again Later", "error");
} else {
swal.stopLoading();
swal.close();
}
});

PHP:

$conn = mysqli_connect(REMOVED FOR PRIVACY);
if($_GET['mode'] === "key") {
$key = htmlspecialchars($_GET['key']);
$query = "SELECT beta_key FROM beta_keys WHERE beta_key = '$key'";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) == 1) {
die(json_encode(['tf' => "true"]));
} else {
die(json_encode(['tf' => "false"]));
}
}

它所做的只是调用函数的.catch部分。提前谢谢。

查看SweetAlert,我不知道为什么它不起作用,但我使用了叉子SweetAlert 2,它让它更容易。我使用了当前的PHP和略有不同的JS。

function SignUp() {
swal({
title: 'Enter Your 8-Digit Beta Key',
input: 'text',
inputAttributes: {
autocapitalize: 'on'
},
showCancelButton: true,
confirmButtonText: 'Submit',
showLoaderOnConfirm: true,
preConfirm: (key) => {
return fetch(`beta/database.php?mode=key&key=${key}`)
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json()
})
.catch(error => {
swal.showValidationError(
`Request failed: ${error}`
)
})
},
allowOutsideClick: () => !swal.isLoading()
}).then((result) => {
if (result.value.tf == "true") {
swal({
type: 'success',
title: 'Key Valid',
text: 'Redirecting',
footer: '<a href="#">Click Here To Go There Now</a>'
})
} else if(result.value.tf == "false") {
swal({
type: 'error',
title: 'Key Invalid',
text: 'Your Key Is Either Inactive Or Typed Incorrectly.',
footer: '<a href="#">Why do I have this issue?</a>'
})
}
})
}

希望这能让处理同样问题的人更轻松。

最新更新