I'm trying to explore the cart of codeigniter. I found some problem which I don't know how to solve it. My only concern is that when i tried to go to incognito mode and add to cart some product it will minus to my stock and when i tried to close my incognito the stock will not get back. What can be the possible solution for that?
Controller
public function validaqty()
{
$this->form_validation->set_rules('qty','Quantity','callback_checkqty');
if($this->form_validation->run()==FALSE):
$validation = array(
'qty_error' => form_error('qty')
);
echo json_encode($validation);
else:
$getprod = $this->CrudModel->get_where('products','id',$this->decrypt);
$cart = array(
'id'=> secret_url('encrypt',$getprod->id),
'name' => $getprod->name,
'qty' => $this->input->post('qty'),
'pouchsize' => $getprod->pouch_size,
'subtotal' => $getprod->price * $this->input->post('qty'),
'weight' => $getprod->weight,
'lbctype' => $getprod->lbc_type,
'stock' => $getprod->stock,
'price' => $getprod->price,
'image' => $getprod->image,
'validate_jquery' => 1
);
$cartinsert = $this->cart->insert($cart);
$lessstock = array(
'stock' => $getprod->stock - $this->input->post('qty')
);
$this->db->where('id',$this->decrypt);
$this->db->update('products',$lessstock);
echo json_encode($cart);
endif;
}
MODEL
public function get_where($table,$primary,$id)
{
$query = $this->db->get_where($table,array($primary=>$id));
return $query->row();
}
JQUERY / AJAX
$("#qty_field").on("keypress",function(key){
if(key.which < 48 || key.which > 57){
key.preventDefault();
}
})
$("#qty_form").on('submit',function(){
var name = $(this).data('name');
$.ajax({
url: base_url +"cart/qty",
type: "POST",
data: $(this).serialize(),
success: function(data){
var result = JSON.parse(data);
if(result.validate_jquery === 1){
var name = result.name;
var qty = result.qty;
// var subtotal = result.subtotal.toFixed(2);
var subtotal = result.subtotal;
var currformat = subtotal.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
$('#qty_err').html("");
$('#qty_field').val("1");
$.notify({
title: '<strong>ADDED TO CART</strong>'+ "<br>",
message: "Product Name: "+name +"<br>"+"Quantity: " + qty +"<br>" + "Total: ₱ " +currformat+"<h5>To checkout, click the shopping cart</h5>",
},
{
type: 'pastel-danger',
delay: 5000,
template: '<div data-notify="container" class="col-xs-11 col-sm-3 alert alert-{0}" role="alert">' +
'<span data-notify="title">{1}</span>' +
'<span data-notify="message">{2}</span>' +
'</div>'
}
);
}else{
$("#qty_err").html(result.qty_error);
}
},
error:function(data){
alert("Oops... Something went wrong :(");
}
});
event.preventDefault();
});
PS: For clarification I just want to know if there is some possible solution to return the stocks if once you tried to add to cart in incognito/private mode of a browser then i just exit it. and also other problem i saw is once the session i think of the cart ends the stock will not return also.
thank you