Reputation: 1883
I'm doing project for online food ordering system. I've made add to cart using session array and its functioning well. I'm using following code to count session so that user can know how many types of item are there in cart.
<?php echo sizeof($_SESSION['cart']); ?>
But using this code I need page to be refreshed for increase in session array count.
Now I want to know that is it possible to count that session array through ajax so that sessions count increases as soon as user add item to cart.
Thank you.
Upvotes: 0
Views: 962
Reputation: 1393
you can done with this,
$.post( "count.php", function( data ) {
console.log(data);
$('#div_id').html(data);
});
and in count.php
<?php
session_start();
echo sizeof($_SESSION['cart']);
?>
demo exapmle,
<html>
<head>
<script>
$.post( "count.php", function( data ) {
console.log(data);
$('.result').html(data);
});
</script>
</head>
<body>
<div class="result"></div>
</body>
</html>
Upvotes: 0
Reputation: 20534
Lets say your php back end is this :
<?php
$session_size = sizeof($_SESSION['cart']);
echo json_encode(array(
'size' => $session_size
));
?>
You can catch this value from client side without page refresh using ajax :
$.ajax({
url: "/url_to_your_page.php",
type: "GET",
contentType: "application/json;",
dataType: "json",
success: function (data) {
console.log(data.size);
},
error: function () {
console.log("Something weird happen");
}
});
Upvotes: 1