Reputation: 1192
I am having 2 portions of code (php and javascript).
In the PHP file, I use the function json_encode()
to create a JSON data
which will be sent to the Javascript file.
PHP FIle
<?php
if(isset($_GET["remove_code"]) && isset($_SESSION["products"]))
{
$product_code = filter_var($_GET["remove_code"], FILTER_SANITIZE_STRING); //get the product code to remove
if(isset($_SESSION["products"][$product_code])) {
unset($_SESSION["products"][$product_code]);
}
$total_items = count($_SESSION["products"]);
if($total_items == 0){
unset($_SESSION["products"]);
}else{
//Calculate total of items in the cart
$total = 0;
foreach($_SESSION["products"] as $product){ //loop though items and prepare html content
$product_price = $product["price"];
$product_quantity = $product["quantity"];
$subtotal = $product_price * $product_quantity;
$total += $subtotal;
}
}
die(json_encode(array('items'=>$total_items, 'total'=>$total)));
}
?>
Javascript File
<script>
$(document).ready(function(){
$(".contentwrapper .content").on('click', 'a.removebutton', function() {
var pcode = $(this).attr("data-code"); //get product code
$.getJSON( "phpfile.php", {"remove_code":pcode}, function(data) {
alert(data.items);// the total number of item
});
});
</script>
Anytime the query $.getJSON( "phpfile.php", {"remove_code":pcode}...
is successful, an alert is displayed showing the data.items
. The problem I am facing is that, when data.items
is greater than or equal to 1 the alert is prompted, but when data.items
is equal to 0, no alert is prompted.
Kindly help me solve this problem
Upvotes: 1
Views: 691
Reputation: 82
Looks like a PHP error. $total variable is only declared inside the 'else' condition, so when ($total_items == 0)
$total is undefined. But as you've called die(json_encode(array('items'=>$total_items, 'total'=>$total)));
the server doesn't have a chance to complain (maybe returning no data and hence no alert). If you try declaring $total = 0
before your condition it should also fix the issue, without having to die early.
Upvotes: 1
Reputation: 1192
Adding die(json_encode(array('items'=>$total_items)));
at the end of the condition if($total_items == 0)
and it solves the problem. But I really can't explain what is happening. Up to now I do not really know the origin of the problem. Any explanation will be welcomed
Upvotes: 0
Reputation: 5176
One possibility is that actually data variable is undefined/null e.t.c., see this for example, second alert is not shown. Instead an error is shown on the browser console.
var data = {items:0};
alert(data.items);
data = null;
alert(data.items);
Upvotes: 0