Văn Lộc Văn Lộc - 1 month ago 15
PHP Question

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

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

I using Ajax to do this, you can see my Ajax code at 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 to 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 will store at 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 will be tried to
foreach
loop through all data in this array and show in 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.

Thanks.

Updated 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.

Updated 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.

Answer

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>