0

I want to store slug values of multiple items in a session array

here is my ajax script through which I am posting slug name to the session:

 <script>
$('a.add_to_cart_button').click(function(){
    var slug = $(this).attr('id');
     $.ajax({
        type: "POST",
        url: "assets/includes/session.php",
        data:{ prod_slug: slug }, 
        success: function(data){
            alert(data);
        }
     });
});
</script>

here is my code of session.php:

<?php
session_start();
 $slug = $_POST['prod_slug'];

 $arr = array('slug'=> $slug);
$_SESSION = array_merge($_SESSION,$arr);
print_r($_SESSION);
?>

But as associative array should have unique key so it is overwriting values:

$arr = array('slug'=> $slug);

the key should have increment to store multiple values like:

$arr = array('slug'=> $slug);

$arr = array('slug1'=> $slug);

$arr = array('slug2'=> $slug);

How do I get this done.

2 Answers2

1

Get what is in the session in an array and then append it back to the session

<?php
session_start();
if(empty($_SESSION['slug'])){
    $_SESSION['slug'] = array();
}
array_push($_SESSION['slug'], $_POST['prod_slug']);
print_r($_SESSION);
?>

This would assume that you initialize $_SESSION['slug'] as an array.

nerdlyist
  • 2,842
  • 2
  • 20
  • 32
1

for community use:

<?php

session_start();

 $slug = $_POST['prod_slug'];
$_SESSION['slugs'][] = $slug;
$_SESSION = array_merge($_SESSION);
print_r($_SESSION);
return false;

?>