Norse
Norse

Reputation: 5757

Unsetting a PHP session with JQuery / AJAX

Button on index page:

$('#killsession').click(function() {
    $.get('killsession.php');
    alert("OK");
});

killsession.php:

<?php
session_start():
session_destroy();
?>

After killing the session with this button, any session-esque related functions on index still work (session variables are still set/exist). For example, I have a counting session variable that is incremented when I click a certain button. This counting variable does not lose its spot in counting after killing the session.

Is it possible to kill a session with a JQuery button?

Upvotes: 4

Views: 10418

Answers (3)

JDavis
JDavis

Reputation: 3318

$('#killsession').click(function() {
  $.get('killsession.php', function() {
    alert("the server page executed");
    //Here you may do further things.

    window.location = window.location;
  });
});

killsession.php

session_start();

$_SESSION = array();

$params = session_get_cookie_params();

setcookie( session_name(), '', time() - 42000,
    $params["path"],
    $params["domain"],
    $params["secure"],
    $params["httponly"]
);

session_destroy();

exit('OK');

Upvotes: 4

Shyju
Shyju

Reputation: 218732

Make sure you are doing other things (like checking session) only inside the call back of ajax function .Whatever inside the callback will be executed after receiving a response from the ajax server page.

$('#killsession').click(function() {
    $.get('killsession.php',function(){
       alert("the server page executed");
       //Here you may do further things.

    });

});

Upvotes: 1

David Lesches
David Lesches

Reputation: 788

All the PHP session items are loaded when the page is first loaded. They are still in the page/browser memory as long as the page is open. You need to reload the page after killing the session. You can do this with javascript window.location.href = window.location.href

Upvotes: 5

Related Questions