I am trying to delete cookies once an "a" is pressed. So I thought of using ajax like this:
<?php
$logged = false;
if (isset($_COOKIE["psw"]) && isset($_COOKIE["usn"])){
$logged = true;
?>
<script>
console.log("status: Logged");
var ahr = document.getElementById('ahr');
ahr.setAttribute('href', '');
ahr.innerHTML="Log-out";
ahr.onclick = function remokecookies() {
$.ajax({
type: "POST",
url: 'bottlesbeach.eu/ajax.php',
data:{action:'removecks'},
success:function(html) {
alert(html);
}
});
}
</script>
<?
Then on the ajax.php:
<?php
if($_POST['action'] == 'removecks') {
setcookie("usn", "", time() - 86400 * 30);
setcookie("psw", "", time() - 86400 * 30);
}
?>
But when I click on the "a" (which is "Logout", see bottlesbeach.eu) the page reloads but the cookies are not deleted (I check the cookies by clicking on cookies> bootlesbeach.eu> cookies).
My question is: why are the "usn" and "psw" cookies not deleted?
My libs:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>
<!--sweet alert lib-->
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
The reason that this doesn't work is that you haven't actually included the jquery
library in you page.
You can fix this by adding the line...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
...to the head of your page.
Additionally you need to change the url
in your ajax request to a relative url
:
`url: '/ajax.php'
Page Refresh
While the above does work to remove the cookies. It doesn't update the page, for example, it still says "log out" in the menu until you refresh the page.
To combat this you should either make the page refresh when the ajax returns...
window.location.href = "/";
...or just set the link to a logout url...
<a href="/logout.php">Log out</a>
...and have that re-direct to the home page...
header("location: /");
Cookie content
You should never store sensitive information like passwords in a cookie, even if you encrypt it first.
Instead you should have a second table that links the user to a long, randomly generated, "session id". The session id is then sent back and forth in the cookie and the user id looked up in the database.
Passwords
I'm not sure how you store passwords on your server, however, they should ALWAYS be stored as a has and not in plain text. You can do this with inbuilt PHP functions...
$password = password_hash($_POST["password"], PASSWORD_DEFAULT);
...and verify the same way...
$loggedon = password_verify($_POST["password"], $db_password);
Effects
You should be careful when using effects to make the website dynamic. Personally I find it really annoying that the "logon" form expands and shrinks when it comes into and out of focus etc.