简体   繁体   中英

How to pass variable from Controller to View with Ajax in Codeigniter?

I have a problem with passing data from Controller to View.

I am using Ajax to do this, you can see my Ajax code here:

$(document).ready(function(){
    $('li.thang').click(function(){
        var id_thang = $(this).attr('value');
        $.ajax({
            url: baseUrl+'/Home/getImage',
            dataType: 'json',
            type: 'POST',
            data: {id_thang: id_thang},
        }).done(function(result) {
            console.log(result.get_list_image_thang);
        })          
    });
});

I will get id_thang when clicking in HTML tags li > thang .

At Controller / Home.php , I will get an array data on this id_thang .

function getImage(){
    $id_thang = $this->input->post('id_thang');
    $input = array();
    $input['order'] = array('id','ASC');
    $get_image_thang  = $this->Mmenushoatnao->get_info($id_thang);
    ob_start();
}

All data is stored in array $get_image_thang .

Finally, I don't know how to pass this array to View show all data I selected.

In View/index.php I am trying a foreach loop through all data in this array and show in <html> tag. Like this:

<?php foreach($get_image_thang AS $item) ?>
    <div class="col-md-4 col-sm-4 col-xs-4">
        <?php echo $item->id; ?>
    </div>
<?php endforeach ?>

Note: at View / index.php is demo code.

Problem is I don't know how to send $get_image_thang to this View.

Update 1:

I tried to put: console.log(result); to .done(function(result) event and receive result like this:

Problem is: I use row += result[i].id; or any property like id , name , image_list is not undefined.

Update 2:

Only two function to get info base on id . I write all code in core/MY_MODEL.php :

function get_info($id, $field = '')
{
    if (!$id)
    {
        return FALSE;
    }

    $where = array();
    $where[$this->key] = $id;

    return $this->get_info_rule($where, $field);
}

function get_info_rule($where = array(), $field= '')
{
    if($field)
    {
        $this->db->select($field);
    }
    $this->db->where($where);
    $query = $this->db->get($this->table);
    if ($query->num_rows())
    {
        return $query->row();
    }

    return FALSE;
}

At controller, I call get_info . Note:

Mmenushoatnao is a Model maps in database.

Update 3:

I only know write code in Controller to get data after click event.

But like your question mention. Must write all code in Ajax code.

Like this:

function getImage(){
    $id_thang = $this->input->post('id_thang');
    $input = array();
    $input['order'] = array('id','ASC');
    $get_image_thang  = $this->Mmenushoatnao->get_info($id_thang);
    ob_start();
    ?>
    <?php foreach($get_image_thang as $item): ?>
    <?php $image_list = json_decode($item->image_list); ?>
    <?php foreach($image_list as $image): ?>
    <div class="col-md-4 col-sm-4 col-xs-4">
        <img src="<?php echo upload_url() ?>/img/hoatnao/hinhanh/<?php echo $image ?>" alt="Image" class="img-responsive">
    </div>
    <?php endforeach; ?>
    <?php endforeach; ?>

    <?php
    $return  = ob_get_clean();
    $data['result']=$return;
    echo json_encode($data);
}

Of course, this code is not working.

So, we need convert to Ajax code.

try this

function getImage(){
    $id_thang = $this->input->post('id_thang');
    $input = array();
    $input['order'] = array('id','ASC');
    $get_image_thang  = $this->Mmenushoatnao->get_info($id_thang);
    echo json_encode($get_image_thang);
}

Now in ajax (assuming you are returning object from get_info() method)

//....
.done(function(result) {
   var row = '';
    for (var i = 0; i < Object.keys(result).length; i++) {
         row +=  result[i].id;
    }
   $('#res').html(row);
 })

before it, provide any ID in your view page where you want to show this result

<div id="res" class="col-md-4 col-sm-4 col-xs-4">

</div>

From what I'm noticing you haven't set your data to JSON output i would recommend you take a look at the output class in the codeigniter guide , Also how you need to decode The JSON in your controller I will leave a reference for you here reading the link will give you a better understanding of how to decode the JSON fore example it takes a second parameter that turn your JSON into an array.

function getImage(){
    $id_thang = $this->input->post('id_thang');
    $id_thang = json_decode($id_thang); // decode JSON to work with it.
    $input = array();// im guessing this is the array you want to send back as JSON
    $input['order'] = array('id','ASC');
    $get_image_thang  = $this->Mmenushoatnao->get_info($id_thang);
    ob_start();// I have no clue you want to achieve with this function? more info on this would be good.

    $this->output
      ->set_content_type('application/json')
      ->set_output(json_encode(array(YOUR ARRAY HERE)));

}

This should be the last thing in your controller for it's the output.I would also like to know if you can share what the console says.

Another thing I noticed is that you don't stringify your data when sending it through $.ajax example ;

    $(document).ready(function(){
        $('li.thang').click(function(){
            var id_thang = $(this).val();
            $.ajax({
                url: baseUrl+'/Home/getImage',
                dataType: 'json',
                type: 'POST',
                // this is where you should stringify your JSON
                data: {id_thang: JSON.stringify(id_thang)},
            }).done(function(result) {
                console.log(result.get_list_image_thang);
            })          
        });
    });

I would like to have more info on what the actuall controller is doing and how your returning your query from the model your using to get a better insight and help your furthermore.

If you want to get json data from remote, you can output your result by

echo json_encode($arr);

It will integrate to the result variable from ajax method, and then handle it as array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM