[英]how to add product in to cart without refresh page
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和javascript。请帮助添加到购物车没有刷新页面有人可以看看我的ajax和addtocart.php
php,ajax,mysql,javascript 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. 我们将改变你的ajax提交流程。
Replace you html anchor tag with below. 用下面的html锚标签替换你。 and add jquery code in your file. 并在您的文件中添加jquery代码。
<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. 我在你的锚标签的数据ID中设置了id。 and remove the onclick function. 并删除onclick功能。 and set javascript: in your href. 并在你的href中设置javascript:
then add jquery block in your script which prevent the anchor tag activity. 然后在脚本中添加jquery块,以防止锚标记活动。 and call the addtocart() function with id which we get from this parameter. 并使用我从此参数获取的id调用addtocart()函数。
please try above solution hopefully it will works. 请尝试以上解决方案,希望它会起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.