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);
}