So currently I am trying to have a SweetAlert pop up that has you enter a key to access the website. I want to have it setup so you put in the key and it runs an AJAX request on a separate PHP page that then returns true or false if that key exists. I did try to use the SweetAlerts example but it is continually erroring out.
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"]));
}
}
All it does is call the .catch part of the function. Thanks in advance.
Looking at SweetAlert I have no clue why it is not working but instead, I used the fork Sweetalert 2 and it makes it way easier. I have it working with the current PHP and slightly different 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>'
})
}
})
}
Hope this makes things easier for people dealing with this same issue.