Reputation:
I am adding items into cart with ajax in codeigniter. My problem is that the cart got updated when i refreshes page. I have ajaxify it to prevent page refresh. but its not happening. My code is right and there is no error. but still its not working. my controller code is
public function add_to_cart()
{
$item_id = $this->input->post('item_id');
$item_name = $this->input->post('item_name');
$item_price = $this->input->post('item_price');
$data = array(
'id' => rand(5,1000),
'qty' => 1,
'price' => $item_price,
'name' => $item_name,
);
$this->cart->insert($data);
}
my view code is
function insert()
{
var item_id=$("#item_id").val();
var item_name=$("#item_name").val();
var item_price=$("#item_price").val();
var dataString = "&item_id=" + item_id + "&item_name=" + item_name + "&item_price=" + item_price;
$.ajax({
type: "POST",
url: "http://localhost/wah/cart_test/add_to_cart",
data: dataString,
success: function()
{
alert('hello');
}
});
}
<form id="form">
<input type="hidden" id="item_id" name="item_id" value={{data.id}}> <input type="hidden" id="item_name" name="item_name" value={{data.item_name}}> <input type="hidden" id="item_price" name="item_price" value={{data.price}}>
<p><a href="#" onclick="insert()" class="btn btn-primary">Add to Cart</a></p>
</form>
Upvotes: 0
Views: 542
Reputation: 782
the concept of the cart is to add the cart array in a session so the php will not feel the changes until you reload the page
so you have to append the table with javascrip
// in controller
public function add_to_cart()
{
$item_id = $this->input->post('item_id');
$item_name = $this->input->post('item_name');
$item_price = $this->input->post('item_price');
$data = array(
'id' => rand(5,1000),
'qty' => 1,
'price' => $item_price,
'name' => $item_name,
);
$this->cart->insert($data);
echo json_encode($data) ;
}
// in your javascript
$.ajax({
type: "POST",
url: "http://localhost/wah/cart_test/add_to_cart",
data: dataString,
success: function(data)
{
// just replace YOUR-TABLE-ID with table id
//and complete the tr you want to append
var tr = "<tr><td>"+data.id+"</td><td>"+data.name+"</td></tr>";
$("#YOUR-TABLE-ID tr:last").after(tr);
}
});
Upvotes: 1
Reputation: 7111
What is happening when you try to use $item_id instead radnom number:
$data = array(
'id' => $item_id,
'qty' => 1,
'price' => $item_price,
'name' => $item_name,
);
Upvotes: 0