Jquery - 带有ajax的产品比较复选框

I try to make a product comparison

  • 1 / the customer check one or several compare checkbox
  • 2 / when a checkbox is displayed, a message appears at the bottom
  • 3 / the value of checkbox is stored under a session

My problem is the ajax, it seems does not insert the checkbox value inside a session.

Thank you.

I started y that

<div><input type="checkbox" value="1" id="P1" /> P1</div>
<div><input type="checkbox" value="2" id="P2" /> P2</div>
<div><input type="checkbox" value="3" id="P3" /> P3</div>

<div id="container" style="display:none;"> 
    <div class="col-md-12 alert alert-info text-md-center">
        <a href="products_compare">Compare</div>
    </div>
</div>

the script

<script>
   $(function() {
$('input[type=checkbox]').change(function(){   
    var chkArray = [];   
    $('#container').html('');

    //put the selected checkboxes values in chkArray[]
    $('input[type=checkbox]:checked').each(function() {
        chkArray.push($(this).val());
    });


    //If chkArray is not empty show the <div> and create the list
    if(chkArray.length !== 0){
        $('#container').show();           
        $.each(chkArray, function(i, val) { 
            $('<p>').text(chkArray[i]).appendTo('#container');

             $.ajax({
                method: 'POST',
                url : "http://localhost/shop/ext/ajax/products_compare/compare.php",
                data : {product_id:chkArray[i]},
                success : function(resp){
                    alert("Product is added to be compared");
                }
            });               
        });
    }else{
        $('#container').hide();   
        $('#container').html('');
    }
});

})

the ajax file

$product_id = $_POST['product_id'];

if(!is_array($_SESSION['ids'])) {
  $_SESSION['ids'] = [];
} else {
  array_push($_SESSION['ids'], $product_id);
}

You need to add session_start(); before you use the $_SESSION variable. You should check if $_SESSION['ids'] is set by using isset().

session_start();
$product_id = $_POST['product_id'];
$_SESSION['ids'] = $product_id;

This should work now, please check it.

Nevertheless, I would restructure your JavaScript code in order to reduce the number of requests send. At the moment, you are sending a separate request for every checkbox checked instead of just sending one array (just remove the $.each loop).

if(chkArray.length !== 0){      
    $.ajax({
            method: 'POST',
            url : "http://localhost/test/test2.php",
            data : {product_id: chkArray},
            success : function(resp){
                alert("Product is added to be compared");
            }
        });  
}

Please keep in mind that you are now adding an array to the array every time you do a POST.

Array
(
    [0] => Array
        (
            [0] => 1
        )

    [1] => Array
        (
            [0] => 1
            [1] => 3
        )

)