0

i want to check existence of a cookie in html, here is my code:

<!DOCTYPE html>
<html>
<head>

</head>
<body>

<div id="a1">
<p id = "ttttt">a1 test</p>
</div>
<script>
function checkCookie() {
   $cookie_name = 'testhastin';

    if(!isset($_COOKIE[$cookie_name])) {

    document.getElementById("ttttt").innerHTML = "set";
} else {

    document.getElementById("ttttt").innerHTML = "not set";
}
}
window.checkCookie(); 
</script>

</body>
</html>

but when i run this page, noting will happen for "a1 test". (meaning it does not change to "not set")

i want to check if a cookie exists on the page and if so show specific content.

i also tried this code and result was the same:

<!DOCTYPE html>
<html>
<head>

</head>
<body>

<div id="a1">
<p id = "ttttt">a1 test</p>
</div>
<script>
function checkCookie() {
    var username = getCookie("testhastin");


    if (username != "") {
    document.getElementById("ttttt").innerHTML = "set";
} else {

    document.getElementById("ttttt").innerHTML = "not set";
}
}
window.checkCookie(); 
</script>

</body>
</html>
Alireza Pir
  • 878
  • 1
  • 16
  • 41

1 Answers1

1

$_COOKIE is a PHP variable. isset() is a PHP functoin. You cannot use that in JavaScript.

As for fetching cookies use document.cookiename

// Setting a cookie
document.testhastin= "Akshay";
// Reading a cookie
var val = document.testhastin;

W3Schools Link : https://www.w3schools.com/js/js_cookies.asp

DollarAkshay
  • 2,063
  • 1
  • 21
  • 39