Macmac Tan Macmac Tan - 13 days ago 5
Ajax Question

$this->input->post() is always empty in codeigniter

I am trying to get a value from an AJAX post that always seems to be empty. I already tried printing the value before doing the post and it works fine but I cannot get the value via $this->input->post()

HTML

<?php if ($product_info->stock > '1'){?>
<button class="btn btn-lg btn-primary" product_id = "<?php echo $product_info->id;?>" id = "addtocart"><i class="fa fa-shopping-cart"></i>Add to Cart</button><?php}?>


Javascript

$(document).ready(function(){
$("#addtocart").click(function(){
var productid = $(this).attr('product_id');

$.ajax({
type: "POST",
url: "<?php echo base_url();?>shoppingcart",
data: productid,
cache: true,
success: function(productid){
$("#cartstatus").html('<div class="alert alert-success"><strong>Success! </strong>Item has been added to the cart.</div>');
}, error: function(productid){
$("#cartstatus").html('<div class="alert alert-danger"><strong>Opps! </strong>Something went wrong.</div>')
}
});
});
});


Controller

$productcart = array();

if($this->session->userdata('cartsession')){
$cartsession = $this->session->userdata('cartsession');

foreach($cartsession as $id=>$val){
$productcart[$id] = $val;
}
}

$productcart[$this->input->post('productid')] = 50; -->sample value
$this->session->set_userdata('cartsession', $productcart);
$cartsession = $this->session->userdata('cartsession');

Answer

data params have certian format for sending values to the server using ajax.

Try this ...

$(document).ready(function(){
    $("#addtocart").click(function(){
        var productid = $(this).attr('product_id');

    $.ajax({
        type: "POST",
        url: "<?php echo base_url();?>shoppingcart",
        data: {productid : productid},
        cache: true,
        success: function(productid){
            $("#cartstatus").html('<div class="alert alert-success"><strong>Success! </strong>Item has been added to the cart.</div>');
        }, error: function(productid){
            $("#cartstatus").html('<div class="alert alert-danger"><strong>Opps! </strong>Something went wrong.</div>')
        }
    });


   });
});