Unable to get Datatables to work with simple JSON data

Unable to get Datatables to work with simple JSON data

deppfxdeppfx Posts: 2Questions: 1Answers: 0

I am unable to plot a simple JSON response to the tables. Can someone please help? I am new to front end coding. This is just an example, My actual nested JSON objects are as big as 3MB/3000 lines.

GET /api/v1/get
{"extn":"5421","name":"Tiger Nixon","office":"Edinburgh","position":"System Architect","salary":"$320,800","start_date":"2011/04/25"}

This is my html code.

!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta name="generator" content=
  "HTML Tidy for Linux (vers 25 March 2009), see www.w3.org" />

  <title></title>
  <link rel="stylesheet" type="text/css" href=
  "https://cdnjs.cloudflare.com/ajax/libs/material-design-lite/1.1.0/material.min.css" />
  <link rel="stylesheet" type="text/css" href=
  "https://cdn.datatables.net/1.10.20/css/dataTables.material.min.css" />
  <link rel="stylesheet" type="text/css" href=
  "https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" />
</head>

<body>
  <table id="table4">
    <thead>
      <tr>
        <th>name</th>

        <th>position</th>

        <th>salary</th>

        <th>start_date</th>

        <th>office</th>

        <th>extn</th>
      </tr>
    </thead>
  </table>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" type=
  "text/javascript">
</script><script type="text/javascript" language="javascript" src=
"https://code.jquery.com/jquery-3.3.1.js">
</script><script type="text/javascript" language="javascript" src=
"https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js">
</script><script type="text/javascript" language="javascript" src=
"https://cdn.datatables.net/1.10.20/js/dataTables.material.min.js">
</script><script type="text/javascript">
//<![CDATA[
  $(document).ready(function() {
  $('#table4').DataTable( {
  ajax: {
    url: '/api/v1/getec2',
    dataSrc: ''
  },
  columns: [
        { "data": "name" },
        { "data": "position" },
        { "data": "salary" },
        { "data": "start_date" },
        { "data": "office" },
        { "data": "extn" }
   ]
  } );
  } );
  //]]>
  </script>
</body>
</html>

Answers

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    Hi @deppfx ,

    It looks like you're returning a single object, not an array of objects as expected. It would be worth looking at this example and comparing what's being sent.

    Cheers,

    Colin

  • deppfxdeppfx Posts: 2Questions: 1Answers: 0

    @colin You are right. That fixed the issue.
    Is there a way to variabilize the ajax URL?

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    Not really, but you can set it to another value with ajax.url()

This discussion has been closed.