when I am trying to click on add to cart button page was reload,i am use php ,ajax and javascript .please help for add to cart without refresh page Can someone please take a look at both my ajax and addtocart.php
php,ajax,mysql,javascript
<?php
if(!empty($cart_data)){
foreach($cart_data as $row){
?>
<div class="product-item">
<div class="pi-pic">
<img src="<?= $row->image ?>" alt="">
<div class="pi-links">
<a href="#" onclick="addtocart(<?= $row->id ?>)" class="add-card"><i class="flaticon-bag" ><span>ADD TO CART</span></i></a>
<a href="#" class="wishlist-btn"><i class="flaticon-heart"></i></a>
</div>
</div>
<div class="pi-text">
<h6>Rs<?= $row->price ?></h6>
<strike>Rs<?= $row->oldprice ?></strike>
<p><?= $row->name ?> </p>
</div>
</div>
<?php
}
}
?>
function addtocart(id){
if(id != ""){
$.ajax({
url:'<?php echo base_url(); ?>home/addtocart',
type:'POST',
dataType:'json',
data:{
'id' : id
},
success: function(data) {
$('.count').html(data.count);
//location.reload();
}
});
} else {
return false;
}
return false;
}
Controller function
public function addtocart(){
$id = $_POST['id'];
$cart_data=$this->Cart->get_cart($id);
$cart_data = json_decode( json_encode($cart_data), true);
$data = array('id' => $id,'qty' => 1,'price' => $cart_data[0]["price"],'name' => $cart_data[0]["name"],'title' => $cart_data[0]["name"],'image'=> $cart_data[0]["image"],'code' => $cart_data[0]["code"],'description'=> $cart_data[0]["description"],);$cart_row = $this->cart->insert($data);
$cart = array_values($this->cart->contents($cart_row));
$data = array('status' => 'Success','count'=>$this->cart->total_items(),);
echo json_encode($data);
}
We are going to change flow of your ajax submission.
Replace you html anchor tag with below. and add jquery code in your file.
<a href="javascript:" data-id="<?= $row->id ?>" class="add-card"><i class="flaticon-bag" ><span>ADD TO CART</span></i></a>
$(document).on('click','.add-card',function(e){
e.preventDefault();
var id=$(this).data('id');
addtocart(id);
});
I had set id in data id of your anchor tag. and remove the onclick function. and set javascript: in your href.
then add jquery block in your script which prevent the anchor tag activity. and call the addtocart() function with id which we get from this parameter.
please try above solution hopefully it will works.