Lee
Lee

Reputation: 1495

jQuery AJAX - Set PHP Session variable

I am looking to store a variable across an entire session so that when a user closes a promotional bar it stays closed and doesn't pop back up every time they navigate to a new page.

On page load I have the following:

$.ajax
({ 
  url: 'promo.php',
  type: 'post',
  data : formData,
  success: function(result)
  {
    alert(result);
  }

});

The formData isn't too important right now as it isn't used.*

promo.php:

<?php

  if (isset($_SESSION['promoBar'])) {

    echo $_SESSION['promoBar'];

  }
  else {

    $_SESSION['promoBar'] = "closed";
    echo "does not exist";

  }

?>

The idea is that on page load it will check if the $_SESSION['promoBar'] variable exists, and if it does, return it's value. Otherwise set a value.

Currently the alert always displays does not exist. I was expecting it to display does not exist the first time and then closed each time I navigate to a new page.

What have I done wrong?

Upvotes: 2

Views: 2356

Answers (1)

Deenadhayalan Manoharan
Deenadhayalan Manoharan

Reputation: 5444

Try this... Use "session_start" before check

session_start();

  if (isset($_SESSION['promoBar'])) {

    echo $_SESSION['promoBar'];

  }
  else {

    $_SESSION['promoBar'] = "closed";
    echo "does not exist";

  }

?>

Upvotes: 3

Related Questions