Sun
Sun

Reputation: 2688

datatables and json formatting error with php

HI im having a little difficulty with dataTables and php. I'm echoing out json in the format below:

{"iTotalRecords":10,"iTotalDisplayRecords":10,"aaData":[[ "1", "15","1","long description long description long description long description"," 2012-02-25 00:00:00"],[ "1", "15","1","long description long description long description long description"," 2012-02-25 00:18:59"] ... ] }

Which inst working with my dataTable, However after validating the above in jsonlint.com/, i get the well formated version below:

   {
            "iTotalRecords": 10,
            "iTotalDisplayRecords": 10,
            "aaData": [
                [
                    "1",
                    "15",
                    "1",
                    "long description long description long description long description",
                    "2012-02-25 00:18:59"
                ],
        ...

            ]
        }

When I put this in a txt file it loads just fine. I also noticed that adding a line break in the "long description" part, it also doesn't work even with the one above. My guess is that the line break is messing with the format of the json, but how can I avoid this in my php script since everything is being word wrapped? I've tried \n in my echo code but it doesnt seem to create a newline.

Upvotes: 0

Views: 4005

Answers (3)

qais
qais

Reputation: 1878

The opening and closing curly braces { and } are not acceptable to DataTables. My guess is, it's considered an object rather than an array. Try this:

Use the following php function to create your JSON array:

$this->arrayJSON = $this->arrayPHPToJS($myArray);

public function arrayPHPToJS($phpArray) { 
    if (is_null($phpArray)) return 'null'; 
    if (is_string($phpArray)) return "'" . $phpArray . "'"; 
    if (self::is_assoc($phpArray)) { 
        $a=array(); 
        foreach ($phpArray as $key => $val ) 
            $a[]=self::arrayPHPtoJS($val); 
        return "[" . implode ( ', ', $a ) . "]"; 
    } 
    if (is_array($phpArray)) { 
        $a=array(); 
        foreach ($phpArray as $val ) 
            $a[]=self::arrayPHPtoJS($val); 
        return "[" . implode ( ', ', $a ) . "]"; 
    } 
    return json_encode($phpArray); 
}

Use this array in JS script in your view (make sure there's no html escaping):

<script type="text/javascript">
    var jsArray = <?php echo $arrayJSON; ?>;

    $(function(){
        var oTable = $('#mytable').dataTable( {
            "aaData": jsArray,
            ....
        });
    });
</script>

Upvotes: 1

Sun
Sun

Reputation: 2688

There seemsed to be an issue with one of my database values, it was starting on a new line, which cause the format of the json to be incorrect.

Upvotes: 0

charlietfl
charlietfl

Reputation: 171679

sounds more like the number of columns set up in table/datatables doesn't match number of items in your json array

Upvotes: 0

Related Questions