how to fetching json array using Ajax Query

how to fetching json array using Ajax Query

AkashvinoAkashvino Posts: 15Questions: 8Answers: 0

Request your help, on how to display a json array using datatables, below is the array type and the code which i tired, but nothing is displayed.

**JSON Array**
{"Server1":
  {
    "2020-01-29":3,
    "2020-01-28":0,
    "2020-01-27":0
 },
 "Server2":
 {"2020-01-29":3,
  "2020-01-28":0,
  "2020-01-27":0
 }
} 

**Ajax Query**
$(document).ready(function(){
var table = $("#Srvtbl").DataTable({
            ajax: {
                    url: "getdata.php",
                    dataSrc: "",
                    method: "GET",
                    xhrFields: { withCredentials: true }
                  },
            columns: [
                        { data: "server[, ]" },
                        { data: "2020-01-29" },
                        { data: "2020-01-28" },
                        { data: "2020-01-27" }
                     ]
});
});     

** Expected Output**
Server Name     2020-01-29    2020-01-28  2020-01-27
Server1              3             0           0
Server2  

Answers

  • kthorngrenkthorngren Posts: 20,302Questions: 26Answers: 4,769

    The problem is your JSON is not in a format Datatables supports. The Ajax docs state this under Data Array Location :

    DataTables requires an array of items to represent the table's data, where each item in the array is a row. The item is typically an object or an array (discussed in more detail below) - so the first thing we need to do is tell DataTables where that array is in the data source.

    Your JSON needs to look more like this:

    [
      {
            "Server": "Server1",
            "2020-01-29": 3,
            "2020-01-28": 0,
            "2020-01-27": 0
        },
        {
            "Server": "Server2",
            "2020-01-29": 3,
            "2020-01-28": 0,
            "2020-01-27": 0
        }
    ]
    

    Kevin

This discussion has been closed.