Codeigniter JSON

Hi, I am using codeigniter and then I exit my database output in my controller and then in my view file I do this:

<script type="text/javascript">
$.getJSON('ajax/forumThreads', function(data) {          
alert(data.overskrift);
});

</script>

but he shows nothing: S

my model file

function forumList()
{
    $this->db->select('overskrift', 'indhold', 'brugernavn', 'dato');
    $this->db->order_by('id', 'desc');
    $forum_list = $this->db->get('forum_traad');

    if($forum_list->num_rows() > 0)
    {
        return $forum_list->result();
    } else {
        return false;
    }
}

my controller

function forumThreads() {

    $this->load->model('ajax_model');
    $data['forum_list'] = $this->ajax_model->forumList();

    if ($data['forum_list'] === true)
    {
        echo json_encode($data['forum_list']);
        $this->load->view('includes/footer', $data); 
    } else {
        return  false;
    }


}
+3
source share
3 answers

$forum_list->result() returns an array of results.

If you only need 1 line, use $forum_list->row(), otherwise in javascript you will need to skip all lines.

$.each(data, function(i,v){
  alert(v.overskrift);
});

EDIT: When outputting JSON, do not print anything before or after. You need to delete $this->load->view('includes/footer', $data);after json_encode. In addition, the controllers do not return anything.

EDIT 2: Replace if ($data['forum_list'] === true)with if ($data['forum_list'] !== false). ===compares the type, and the array is not logical.

+3
source

Model:

function forumList()
{
    $this->db->select('overskrift', 'indhold', 'brugernavn', 'dato');
    $this->db->order_by('id', 'desc');
    $forum_list = $this->db->get('forum_traad');

    if($forum_list->num_rows() > 0)
    {
        return $forum_list->result_array();
    } else {
        return false;
    }
}

:

function forumThreads() {

    $this->load->model('ajax_model');
    $data['forum_list'] = $this->ajax_model->forumList();

    if ($data['forum_list'] !== false) {
        echo json_encode($data['forum_list']);
    }
}
0

:

//works only with php 5.3
echo json_encode($data['forum_list'], JSON_FORCE_OBJECT);
0

Source: https://habr.com/ru/post/1783893/


All Articles