Khuzema
Khuzema

Reputation: 23

php session array not adding new elements using ajax

I'm creating an ticket booking application. I'm trying to create a basic cart using PHP and Ajax, When i click on the add to cart button, It sends the seat number to the "seatchecker.php" file using Ajax which checks if the seat is available, Then if it's available, It sends that seat number to the "seatadder.php" file using Ajax which should add the seat number to the Session array. But each time i click "Add to cart" it just displays the new value, Rather than showing the whole cart. May be it's overwriting the session variable each time? any help would be appreciated. Thanks

<?php
session_start();
// Getting the value sent by checkseats.php using ajax
$seat_added = $_GET['seatadd'];
// ARRAY OF SESSION VARIABLE
$_SESSION['seat_add'] = array();
function multiple_seats_adder($getseat){
  array_push($_SESSION['seat_add'],$getseat);
  // TESTING
  print_r($_SESSION['seat_add']);
  // TESTING
  echo sizeof($_SESSION['seat_add']);
}
echo multiple_seats_adder($seat_added);
?>

Upvotes: 2

Views: 63

Answers (1)

Poiz
Poiz

Reputation: 7617

The Problem seems to stem from the Fact that you are initializing the seat_add Key to an Empty Array each time the Script is called. Most likely, that is not what you want. Consider the Code below:

    <?php
        session_start();
        // Getting the value sent by checkseats.php using ajax
        $seat_added = $_GET['seatadd'];

        // ONLY INITIALIZE THIS TO AN EMPTY ARRAY IF IT DOESN'T EXIST AT ALL:
        if(!isset($_SESSION['seat_add'])){
            // ARRAY OF SESSION VARIABLE
            $_SESSION['seat_add'] = array();                
        }


        function multiple_seats_adder($getseat){
            array_push($_SESSION['seat_add'], $getseat);
            // TESTING
            print_r($_SESSION['seat_add']);
            // TESTING
            echo sizeof($_SESSION['seat_add']);
        }
        multiple_seats_adder($seat_added);

Upvotes: 1

Related Questions