Nadeem Ahmad
Nadeem Ahmad

Reputation: 745

How to destroy PHP Sessions Using Javascript Ajax

I am making a simple login functionality in my website. What I am doing is, when the login is successful, I make a session in php using session_start() and then I define $_SESSION variables where I store the user data. And that $_SESSION data has been sent in response to the ajax call made to login. The login is successful, but when I try to logout a user, I simple send an ajax request, when the logout button is clicked. And there the session_unset() and session_destroy() has been called. Instantly I want to destroy the session I made on login, but it gives me the error : Trying to destroy uninitialized session; I don't know what could be the problem, I have followed some question over here but couldn't solve the problem.

AJAX Call

$(document).on("click", "#logout", function(e) {
  fetch("Models/auth.php", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      "model": "auth",
      "action": "logout",
      "data": null
    })
  }).then(function(t) {
    t.text().then(function(res) {
      console.log(res);
      // if(r.success){
      //     location.href = "register.html";
      // }
    })
  })
})

The PHP

class Globals {

  public
  function makeSession($email, $id, $auth_key, $online, $session) {
    if (!isset($_SESSION)) {
      session_start();
      $_SESSION["user_email"] = $email;
      $_SESSION["user_id"] = $id;
      $_SESSION["user_key"] = $auth_key;
      $_SESSION["user_online"] = $online;
      $_SESSION["user_session"] = $session;
    }
  }

  public
  function destroySession() {
    session_unset();
    session_destroy();
  }


}

if (isset($data)) {

  $conn = new Database;
  $db_conn = $conn - > connect();

  switch ($data - > model) {
    case "auth":
      {
        $auth = new Auth(json_decode($data - > data), $data - > action);
        switch ($data - > action) {
          case "register":
            {
              $auth - > registerUser($db_conn);
              break;
            }
          case "login":
            {
              $auth - > loginUser($db_conn);
              break;
            }
          case "logout":
            {
              $g = new Globals();
              //Call to destroy The Sessions
              $g - > destroySession();
              echo json_encode(array("success" => true, "action" => "logout"));
              break;
            }
        }
        break;
      }
  }

}

Upvotes: 0

Views: 1199

Answers (2)

Dupinder Singh
Dupinder Singh

Reputation: 7759

A simple solution that you can try

session_start();

We have to add this on the top of php file, or else php throw exceptions like 'headers already sent' or 'can’t start the session' etc.

So have 2 options 1. Add session_start(); in class public function like

  public
  function destroySession() {
    session_start();
    session_unset();
    session_destroy();
  }

or 2. just add session_start(); in before Switch case; and your code will look like

if (isset($data)) {

  $conn = new Database;
  $db_conn = $conn - > connect();
  session_start();
  switch ($data - > model) {
    case "auth":
      {
        $auth = new Auth(json_decode($data - > data), $data - > action);
        switch ($data - > action) {
          case "register":
            {
              $auth - > registerUser($db_conn);
              break;
            }
          case "login":
            {
              $auth - > loginUser($db_conn);
              break;
            }
          case "logout":
            {
              $g = new Globals();
              //Call to destroy The Sessions
              $g - > destroySession();
              echo json_encode(array("success" => true, "action" => "logout"));
              break;
            }
        }
        break;
      }
  }

Upvotes: 1

pauldrodriguez
pauldrodriguez

Reputation: 490

in order to destroy the data for a session, you need to initialize/resume the session, otherwise you wont be able to get the session. so you will need to call session_start().

so try this code:

 public function destroySession() {
    session_start();
    session_unset();
    session_destroy();
  }

Upvotes: 1

Related Questions