This is a migrated thread and some comments may be shown as answers.

Binding JSON data fetched from php file to a grid

1 Answer 594 Views
Data Source
This is a migrated thread and some comments may be shown as answers.
Wern
Top achievements
Rank 1
Wern asked on 15 Jan 2012, 01:57 AM
I'm having problems in binding a json data fetched from a php file to a grid. Here's what my php file looks like:
$studs = array();
$db->query("SET CHARACTER SET utf8");
$students = $db->get_results("SELECT * FROM tbl_participants");
if(!empty($students)){
    foreach($students as $k=>$v){
         
        $studs['participant'][] =  $v->participant;
    }
}
echo json_encode($studs);

And here's the file where I have the grid:
<script>
 $(document).ready(function() {
   var dataSource = new kendo.data.DataSource({
    transport: {
     read: {
      
      url: "fetch_data.php",
      dataType: "json"
     }
    },
    schema: {data: "participant"}
   });
  
   $("#grid").kendoGrid({
    dataSource: dataSource,
     height: 360,
     groupable: true,
     scrollable: true,
     sortable: true,
     pageable: true,
     autoBind:true,
     columns: [
         
        {field: 'participant', title: 'Name'}
         
     ]
      
   });
 });
</script>
<table id="grid"></table>

1 Answer, 1 is accepted

Sort by
0
Andrew
Top achievements
Rank 1
answered on 16 Jan 2012, 01:00 AM
You might try to build your JSON result like the below.   Note you want to also capture the number of rows returned in a separate result of your JSON so that you can have like like  ' totals: "totals" ' in you datasource definition.   Also note that I am using the PHP settype() function to make sure the numbers get placed into the JSON as numbers (not strings) - this, combined with defining them as numbers in your Model, will let the Kendo grid sort/filter them properly (as numbers, not strings)...

$sql = "SELECT account_id, account  FROM accounts";

$result = mysql_query($sql) or die(mysql_error());  

    $num_rows = mysql_num_rows($result);
    $account_recs = array();
if(mysql_num_rows($result)) {
   while($account_rec = mysql_fetch_assoc($result)) {
   settype($account_rec["account_id"], "integer");
    array_push($account_recs, $account_rec);
 }
    }

header('Content-type: application/json');
echo json_encode(array('account_recs'=>$account_recs, "totals"=>$num_rows));
     
Tags
Data Source
Asked by
Wern
Top achievements
Rank 1
Answers by
Andrew
Top achievements
Rank 1
Share this question
or