Ishrak
Ishrak

Reputation: 71

Populating a datatable with json data using javascript in codeigniter

I am starting to learn javascript.

Controller file:

 public function index(){  

    $this->load->view('crud_view.php');

    $this->load->model('pushnotification_model');

    $data['jsonData'] = json_encode($this->pushnotification_model->search_user());

    $this->load->view('pushnotification_group_wise_view',$data);
}

search_user is a method in the model pushnotification_model which retrieves data from the database and returns back to the controller for json encoding.

Now in the pushnotification_group_wise_view I have a table like below:

  <div id="showUserData" data-bind="visible: records().length > 0">
  <table class="table table-striped table-bordered">
    <thead>
        <tr>
            <th>GCM REG ID</th>
            <th>EBL SKY ID</th>
        <th style="text-align:center"><button data-bind="click :$root.processAll" class="btn btn-primary">Select All</button></th>
        </tr>
    </thead>
    <tbody data-bind="foreach: records">
        <tr>
            <td data-bind="text:gcm_regid"></td>
            <td data-bind="text:eblSkyId"></td>
            <td style="text-align:center"><input type="checkbox" data-bind="checked: isProcessed"></td>
        </tr>
    </tbody>
  </table>

Now I want to populate the table with the $data using javascript. How can I do that?

Upvotes: 1

Views: 831

Answers (1)

Saqueib
Saqueib

Reputation: 3520

Since your pushnotification_group_wise_view is already have the jsonData you can do it using php no need to use javascript, but To do it using JavaScript you will need an endpoint to access the data result in json format

in controller

public function notification(){  

   $this->load->model('pushnotification_model');

   //return data as json 
   $this->output
           ->set_content_type('application/json')
           ->set_output( json_encode($this->pushnotification_model->search_user()) );
}

in JS using jQuery

$.getJSON( "/notification", function( data ) {

    $.each( data, function( key, val ) {
         //do the iteration and built the rows of  table for population here 
    });

    //and at last append it to `$('#showUserData table')`
});

Upvotes: 1

Related Questions