0

I'm newbie to php, I would like to delete cookies with onClick event, I'm trying with some code but it doesn't work, this is what I tried, how can I fix it for it to work?

<html>
<head>
<body>

<button id="button" onClick='deleteCookie()'>Delete</button>

<script>

function deleteCookie(){
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if ( xmlhttp.readyState == 4 ) { 
            if ( xmlhttp.status == 200 ) { 
                unset($_COOKIE['user']);

            } 
        } 
xmlhttp.open( "GET", "cookie.php", true ); 
xmlhttp.send();

    }
}
</script>

</body>
</head>
</html>

2 Answers2

0

I am not sure if you are trying to put PHP code into Javascript there or just trying to show what PHP is done at that moment but, In order to "unset" a cooking you simply update the cooking forcing it to expire for example:

   setcookie("user", "", time()-1);

That will set the Cookie to expire 1 second ago and the browser should remove it.

Marky Ross
  • 41
  • 5
0

Just to add-on. Instead of deleting the cookie. What you can do is to set the cookie expiry date in the past. This will trigger the removal mechanism in web browser.

You can do something like this

function deleteCookie(name) {
  document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
}

var cookieName = 'CookieYouCreated';
deleteCookie(cookieName);
Frederickcjo
  • 323
  • 1
  • 9