Reputation: 25
I'm making my first website and I've encountered a problem with AJAX. I have tried and searched a lot of things but I'm missing something, please help me on this one. I have products' count and it works fine, but I need to refresh page everytime when I add new product to cart to see difference, so I need to use AJAX on my php variable. Please help me write AJAX code. I really appreciate it, thanks a lot and have a good day!
PHP Code:
<?php
$cart = new cart();
$products = $cart->getCart();
$sum = 0;
foreach($products as $product){
$sum += $product->count;
}
echo $sum;
?>
Upvotes: 0
Views: 1608
Reputation: 439
This can be done by adding the following code
$.ajax({
type: "GET",
url: "your url",
data: "",
success: function () {
setInterval(functionName,timeInMilliseconds);
}
functionName=function(){
//your code comes here which you want to get refreshed
}
Using this code after a flag which will test with an if condition that the product count is updated or not. Cheers.
Upvotes: 0
Reputation: 3093
You could perform an ajax request like this. Your php will return the content which can then be appled to the DOM.
// create array to POST
aData = {
AjaxRequest:true,
PostField2:'content',
}
// perform ajax request
$.ajax({
type: "POST",
url: "/relative_path_to_script/",
data: aData,
cache: false,
success : function(data){
console.log( 'response:' + data );
$('#cartCountID').html(data);
},
failure : function(data){
// report any ajax errors
},
complete : function(data){
// runs once on completion
}
});
Upvotes: 1