Ajax data formatting help

Ajax data formatting help

TonyRTonyR Posts: 27Questions: 6Answers: 0

The page: https://datatables.net/examples/data_sources/ajax.html, the 'Ajax' tab, has an example of an acceptable format for use in a Datatables table. I am fairly comfortable with sourcing data via MySQL now, but I have been struggling with getting data direct from text or CSV data and then outputting into the proper format. Here I am beginning with text data and processing it into array format with explode() and then into json data with json_encode() but my output from that doesn't contain the same pattern of brackets surrounding array data as those in the example above. At this point (with the code included here), I am receiving:

{"data":["Fruit, Apple","Fruit, Pear","Fruit, Orange","Berries, blue","Berries, black","Berries, goose","Berries, choke"]}

I am thinking that I need to have it look like:

{"data":[ ["Fruit, Apple"], ["Fruit, Pear"], ["Fruit, Orange"] .... ]}

My goal is to produce a DataTables table with a single column that contains:

     Fruit Apple
     Fruit Pear
     Fruit Orange
     Berries Blue
     Berries Black
     Berries Goose
     Berries Choke

My real-life project is dealing with something under 4,000 records.

Can you please check out http://live.datatables.net/kaladidi/1/ to see what I have manually come up with, and tell me what is wrong with my code there?

Back at home, I have as my Ajax (server side) program named my_data.php:

<?php
// NAME: my_data.php
the_data();  // I have embedded the raw data in a function

$array_data = explode("\n", del_empty_lines($all_data));   // convert data so 
foreach ($array_data as $key=>&$category) {            // category is on same
    if (!preg_match("/^[\s]/", $category)) {                // line
        $tmp_category = $category;
        unset($array_data[$key]);
    } else {
        $category = $tmp_category . ', ' . ltrim($category);
    }
} 
$my_data = array_values($array_data); // reset keys to 0,1,2, etc
// I have embedded the json_encode() function with an array of an array, hoping
// to get those brackets, but I know it's not correct.
$my_data = json_encode(array('data'=>$my_data));     //   <---- I think this is my problem

echo $my_data;    <--- final output for DataTables

function del_empty_lines($string) {
    return preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $string);
}

function the_data() {
global $all_data;
$all_data = "
Fruit
   Apple
   Pear
   Orange
Berries
   Blue
   Black
   Goose
   Choke
";
}

And here is my HTML/php file:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>YummyFood</title>
<! --  
       All script and css source files removed for brevity 
-->
<script>
$(document).ready(function() {

    // As a test, this worked:
    // var my_data = [
    //     ["Applesauce"],
    //     ["Peas and Carrots"]
    // ];

    $('#mainlist').DataTable( {
        processing: true,
        ajax: 'my_data.php',     
        //data: my_data,                  // I don't know if I need these statements
        // columns: [
        //    { data:'Category' }
        // ]
    });
});
</script>
</head>
<body>
<table id="mainlist" class="display">
     <thead>
         <tr>
             <th>Category</th>
         </tr>
     </thead>
     <tbody>
         <tr>
             <td>Category</td>
         </tr>
    </tbody>
</table>
</body>
</html>

Any assistance would be greatly appreciated. And I am definitely having fun.

This question has an accepted answers - jump to answer

Answers

  • TonyRTonyR Posts: 27Questions: 6Answers: 0

    I have made a lot of progress. My solution was to add to a new array in my foreach loop like this:

    foreach ($array_data as $key=> &$category) {
        if (!preg_match("/^[\s]/", $category)) {
            $tmp_category = $category;
        } 
        $final_data[] = array('cat' => $tmp_category, 'subcat'=>ltrim($category));
    } 
    
    $it = json_encode(array('data' => $final_data));
    print_r($it);
    

    At the same time, broke it up into two element column which was what I was planning to do anyway. Thanks for reading. Live and learn.

  • allanallan Posts: 63,455Questions: 1Answers: 10,465 Site admin
    Answer ✓

    Yes, DataTables needs each item in the data array to be a row. So in your first JSON there is a single string representing each row. Your approach of then converting that into how you want the DataTable to display that in rows sounds like the correct one in this case to me.

    Allan

  • TonyRTonyR Posts: 27Questions: 6Answers: 0

    Many thanks, Allan. My understanding is much better now.

This discussion has been closed.