I am trying to make a function with HTML, JS and PHP that does the following:
$_GET
array;$_GET
array it pops up a JavaScript confirm window;$_COOKIE
array the value of true
. If the user presses "CANCEL" JS gives to $_COOKIE
array the value of false
;$_COOKIE
array is checked with PHP, and if it is true
it does something. Otherwise it doesn't do nothing.Where is the code for each step:
// STEP 1
<a href="page.php?remove=true&id-organ=1">Remove</a>
// STEP 2 AND 3
if (isset($_GET['remove']) && isset($_GET['id-organ'])) {
echo '
<script>
var option = confirm("REMOVE?");
if (option == true) {
document.cookie = "option = true";
} else {
document.cookie = "option = false";
}
</script>
';
}
// STEP 4
if ($_COOKIE['option'] == true) {
echo '
<script>
window.alert("ORGAN WAS REMOVED!\n");
</script>
';
}
If JS Confirm Window "OK" is pressed everything works fine, awesome, with no problem.
If JS Confirm Window "CANCEL" is pressed, the STEP 4 if statement happens anyway.
console.log(option)
which is false for CANCEL
button.echo $_COOKIE['option']
wihch is also false
for CANCEL button.This make no sense being literally against all"programming physics". . .
Can someone tell me why is this happening? Am I doing something wrong? Is there a better way for this type of functionality?
The cookie value you set in JS is always a string. (Cookie content is mere text, by definition. No one stops you to interpret that value as something else, after you received it in string form - you could for example set a JSON-encoded object as the cookie value. But that doesn’t change the fact, that the value of the cookie itself, is and will always be text.)
if ($_COOKIE['option'] == true)
Your comparison in PHP is wrong here - because here, you are not comparing with a string.
The text values 'true'
and 'false'
are both truth-y in PHP - 'true' == true
and 'false' == true
both yield true.
What you need here, is if ($_COOKIE['option'] == 'true')
(or even with ===
, to make absolutely sure there is no ambiguity whatsoever.)