4

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.

4
  • could be a duplicate of stackoverflow.com/questions/23776918/… Commented Oct 13, 2016 at 2:12
  • @exiang no duplicate. your reference link is pass data from a controller to Ajax. In this question, I tried to get data from controller and send back to View. Commented Oct 13, 2016 at 2:18
  • $this->Mmenushoatnao->get_info($id_thang); show this get_info() method code Commented Oct 13, 2016 at 4:12
  • I updated get_info() function. Commented Oct 13, 2016 at 4:14

3 Answers 3

3

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>
Sign up to request clarification or add additional context in comments.

5 Comments

I want to show all values of JSON. Seem it only print like: [object Object] 1 or object Object] 2.
Use result.id (in ajax done) as you are using row() in model which returns only a single row from dataset (first row). If you need all results then use result() (in model) instead row()
sorry couldn't realize what you want to say
That mean: I don't know how to add <html> tag like: <div class="col-md-4 col-sm-4 col-xs-4"> or convert a JSON to an array with php code: <?php $image_list = json_decode($item->image_list); ?>. I see your answer can be access to all property of JSON through by Ajax code. And I don't know how to write this code in Ajax code. Are you know my problem?
1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.