• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Creating JSON to be consumed by jQuery DataTables

#1
[eluser]Steve Wright[/eluser]
jQuery DataTables can be populated via ajax containing JSON object with aaData array. The script in by view is..

Code:
$(document).ready( function () {
          $('#dt_test').dataTable( {
          "sAjaxSource":  "<?= base_url() ?>/datatables/ajaxpagelist",
          "aoColumns": [
            { "mdata": "pk_pages"},
            { "mdata": "name"},
            { "mdata": "ts"}
          ],
          "sScrollY": "200px",
          "bPaginate": false
          } );
      } );

I'm creating the JSON response the following controller function...

Code:
function ajaxpagelist() {
    $query = $this->pages_model->get_all_pages() ;
    $obj = new StdClass() ;
    $ojb->aaData = $query->result_array() ;
    $data['json']= json_encode($ojb);
    $this->load->view('json_view',$data)  ;
  }

and view...

Code:
<?php
  $this->output->set_header('Cache-Control: no-cache, must-revalidate');
  $this->output->set_header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
  $this->output->set_header('Content-type: text/plain');      
  echo($json);
?>

The problem is that DataTables returns an error that it cannot parse JSON as it is improperly formatted. I have checked the formatting in JSONLint to confirm that the output is properly formatted. Further, if I copy/paste the JSON in a text file and serve it directly, everything works. Am I missing something in creating and sending the JSON through CI?

#2
[eluser]LinkFox[/eluser]
Can you post the JSON string bring produced? I think I just used to echo the JSON string from the controller Wink

#3
[eluser]Steve Wright[/eluser]
Code:
{"aaData":[{"pk_pages":"1","name":"home","ts":"2009-05-12 19:44:42"},{"pk_pages":"2","name":"results","ts":"2009-05-17 20:47:26"},{"pk_pages":"3","name":"rules","ts":"2009-05-17 22:23:58"},{"pk_pages":"4","name":"draw","ts":"2009-05-19 22:14:52"},{"pk_pages":"5","name":"entry_temp","ts":"2009-05-19 22:17:14"},{"pk_pages":"6","name":"okc2008_q1","ts":"2009-05-19 22:42:57"},{"pk_pages":"7","name":"okc2008_q2","ts":"2009-05-20 10:54:09"},{"pk_pages":"8","name":"okc2008_shootout","ts":"2009-05-20 12:33:43"},{"pk_pages":"9","name":"okc2008_y1","ts":"2009-05-20 13:38:14"},{"pk_pages":"10","name":"okc2008_y2","ts":"2009-05-20 13:38:14"}]}

#4
[eluser]LinkFox[/eluser]
$this->output->set_header('Content-type: text/plain');

Should be

$this->output->set_header('Content-type: application/json');

To start.

The documentation here shows a different JSON format to what you're returning.

http://datatables.net/release-datatables.../ajax.html


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.