admir
admir

Reputation: 193

codeigniter ajax not setting sessions asynchronously

I am new to codeigniter ajax and i have a problem with sessions.My sessions are not being set and unset asynchronously and i have to refresh the page just to see the changes.

view/header:

    <?php
if(!empty($product)){
$pid=$product[0]['product_id'];

}

?>
<script>
$(document).ready(function(){
    if($('.add_to_basket').find('img')){
$('.add_to_basket').click(function(){
        var message=$('#badgemessage');
    $('#msgcart').append(message);
    message.show('slow');
    var trigger=$(this);
    var param=trigger.attr("rel");
    var item=param.split("_");
            $.ajax({

                type: 'POST',
                url: '<?= base_url()."cart_c/myfunk/".$pid?>',

                data: { id: item[0], job: item[1] },
                dataType:'json',
                success: function(data) {
                           console.log(data);       
                },
                error:function(){
                alert("error");
                }
            });
            return false;

});
    }
});



</script>

model/basket_model:

<?php
class Basket_model extends CI_Model{

    function activeButton($sess_id){
        $e=$this->session->userdata('basket');
        if(isset($e[$sess_id])){
        $id=0;
        $label="<img src='".base_url()."images/remove.png' />";
        }else{
            $id=1;
            $label="<img src='".base_url()."images/add.png' />";
        }
        $out="<a href='#' class='add_to_basket' rel='".$sess_id."_".$id."'>".$label."</a>";
        return $out;
    }

    function setItem($pide,$qty=1){
        $e=$this->session->userdata('basket');
        if(isset($e)){
    $e[$pide]['qty']=$qty;
    $this->session->set_userdata('basket',$e);
        }else{
            $arr=array($pide=>array('qty'=>$qty));
            $this->session->set_userdata('basket',$arr);
        }
}
    function removeItem($pide,$qty=null){
        $e= $this->session->userdata('basket');
        if($qty != null && $qty < $e[$pide]['qty']){
            $e[$pide]['qty']=($e[$pide]['qty']-$qty);
            $this->session->set_userdata('basket',$e);
        }else{
            $e[$pide]=null;
            unset($e[$pide]);
            $this->session->set_userdata('basket',$e);


        }

    }
}
?>

controller/cart_c:

<?php
class Cart_c extends CI_Controller{

    function __construct(){
        parent::__construct();
        $this->load->model('catalogue_model');
        $this->load->model('products_model');
        $this->load->model('basket_model');


    }

    function myfunk($id){
    if(isset($_POST['id']) && isset($_POST['job'])) 
    $out=array();
    $pid=$_POST['id'];
    $job=$_POST['job'];
        if(!empty($id)){
            switch($job){
                case 0:
                $this->basket_model->removeItem($pid);
                $out['job']=1;
                break;

                case 1:
                $this->basket_model->setItem($pid);
                $out['job']=0;
                break;

            }
            echo json_encode($out);
        }


    }


}

?>

controller/products:

<?php
class Products extends CI_Controller{
    function __construct(){
        parent::__construct();
        $this->load->model('catalogue_model');
        $this->load->model('products_model');
        $this->load->model('basket_model');
    }

    function product($id){
    $kitties['cats']=$this->catalogue_model->get_categories();
    $data['product']=$this->products_model->get_product($id);
    $data['active_button']=$this->basket_model->activeButton($id);
        $this->load->view('header',$data);
        $this->load->view('sidebar',$kitties);
        $this->load->view('product',$data);
        $this->load->view('footer');
    }

}

?>

view/product:

<div class="contentwrap">
<div id="content_area">
<?php 

$e=$this->session->userdata('basket');
print_r($e);
if(!empty($product)){
    foreach($product as $p){
        ?>
        <h1><?=$p['product_name']?></h1>
        <div id="product_image">
        <img src="<?=base_url()?>/images/<?=$p['image']?>" width="400" height="300" />
        </div>
        <div id="product_desc">
        <?=$p['description']?>
        <br><br>
        <?=$active_button?>


        </div>
        <?php

    }

}else{
    echo "Product unavailable";
}?>




</div>
</div>

The problem is my $active_button in the product view is not changing asynchronously but the sessions are being set and unset i can see items being pushed into and out of the session array when i refresh the page.When i hit the button my chrome console displays: object{job:0}

Upvotes: 1

Views: 972

Answers (2)

CodeGodie
CodeGodie

Reputation: 12132

ok after looking and studying youre code. you can implement what you want by retrieving the button again when making your AJAX call. The way to retrieve it is by calling that model again, then using jquery to replace the current button. Try the following:

Controller - Cart_c

function myfunk($id) {
    if (isset($_POST['id']) && isset($_POST['job'])) {
        $out = array();

        $pid = $_POST['id'];
        $job = $_POST['job'];
        if (!empty($id)) {
            switch ($job) {
                case 0:
                    $this->basket_model->removeItem($pid);
                    $out['active_button'] = $this->basket_model->activeButton($pid);
                    break;

                case 1:
                    $this->basket_model->setItem($pid);
                     $out['active_button'] = $this->basket_model->activeButton($pid);
                    break;
            }
            echo json_encode($out);
        }
    }
}

JS in header view:

<script>
    $(document).ready(function() {

        function add_to_basket($this) {
            var param = $this.attr("rel");
            var item = param.split("_");
            $.ajax({
                type: 'POST',
                url: '<?= base_url() . "cart_c/myfunk/" . $pid ?>',
                data: {id: item[0], job: item[1]},
                dataType: 'json',
                success: function(data) {
                    console.log(data);
                    $this.replaceWith(data.active_button);
                    $('.add_to_basket').click(function() {
                        add_to_basket($(this));
                    });
                },
                error: function() {
                    alert("error");
                }
            });
            return false;
        }

        $('.add_to_basket').click(function() {
            add_to_basket($(this));
        });

    });
</script>

Upvotes: 1

CodeGodie
CodeGodie

Reputation: 12132

Ok I think perhaps we should start by discussing the proper flow of your app. Assuming that your URL looks something like this Products/product/10 and you intially load the page, your function runs providing you with right button and products as expected.. Lets say in this case product 10 does not exist in the session/cart so you see the ADD image button come up.. All good.. Now, when you click add, and from what you are saying, it adds the product to the session/cart, and you get a return JSON of ‘job:0’. So far it works as expected from the code I am seeing. A return of job:0 means that you ran the setItem function. Now the problem you are saying is that the view “is not changing asynchronously”. By this, do you mean that you expect the page to reload and run the function again so that the image can now say “remove”?

Upvotes: 1

Related Questions