Ajax sourced data

Ajax sourced data

gmstephanegmstephane Posts: 4Questions: 3Answers: 0

Hello
how can i read from ajax sourced data with unknown header colonne. I mean the data i get from database can varie en terms of number of column. so i need the columns in the table to be dynamically created from javascript.

Answers

  • kthorngrenkthorngren Posts: 20,425Questions: 26Answers: 4,794

    See this FAQ. Here is a simple example:
    https://live.datatables.net/huyexejo/1925/edit

    It derives the column names from the object keys in the row data. You could return a specific object with the column header names. Use columns.title to define the header names.

    Kevin

  • gmstephanegmstephane Posts: 4Questions: 3Answers: 0

    Hello kthorngren
    Thank you for your quick reply. it put me on the right track.
    But one more, in the example https://live.datatables.net/huyexejo/1925/edit is there a particular format of the json data to be used in the javascript?
    here is a sample of the code

            $rank= 1;
    
            $code_selected =$_SESSION['code'];
            
            $sql_da2 = "SELECT * FROM `donnees` WHERE `id_source`='$code_selected'";
            $rs_da2 = $conP_bdcc->query($sql_da2);
    
            $data = array();
            $annees_inventaire = 2022;
            $annees_temporelles=1990;
    
    while ($row_da2 = $rs_da2->fetch_assoc()) {
    
        $data[] = array(
            "rank" => $rank,
            "annee_inv" => $annees_inventaire,
            "annee_tempo" => $annees_temporelles,
            "code" => $_SESSION['code'],
            "valeur" => $row_da2['valeur'],
            "unit" => $row_da2['unit'],
            "libelle" => $_SESSION['libelle']
        );
    
        $rank++;
    }
    
    
            $datax = array('data' => $data);
            echo json_encode($datax);
    
    
  • kthorngrenkthorngren Posts: 20,425Questions: 26Answers: 4,794

    The Ajax docs provide details of what Datatables expects for the row data. The example I provided simply uses the first object in the array to build the column headers from the object keys.

    If this doesn't do what you want you can return the header names in a different object along side the data object. Since this is something you are adding and Datatables doesn't use it you can return any format that works for your solution.

    Kevin

Sign In or Register to comment.