JSON format for Datatable is not recognized as valid

I am attempting to set up a server-side datatable, but I keep getting an error message saying "Invalid JSON format."

Content Delivery Network (CDN)

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">

HTML

<table id="example" class="display" style="width:100%">
    <thead>
        <tr>
            <th>EmployeeCode</th>
            <th>EmployeeName</th>
            <th>ManagerName</th>
            <th>DesignationName</th>
        </tr>
    </thead>
</table>

JavaScript

<script>
$(document).ready(function() {
    $('#example').DataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": "/api/url",
        "columns": [
            { data: "EmployeeCode" },
            { data: "EmployeeName" },
            { data: "ManagerName" },
            { data: "DesignationName" }
        ],
    } );
} );
</script>

JSON Data

{
  "Results":[{"EmployeeCode": "12345"}], // This is just a sample of data
  "CurrentPage": 1,
  "PageCount": 42,
  "PageSize": 10,
  "RecordCount": 417
}

Answer №1

Upon inspecting the JSON response from the XHR/Ajax call to the server, it becomes evident what the issue is. The expected data structure should look something like this:

[
  {'EmployeeCode':12345, EmployeeName:'abcde',...},
  {'EmployeeCode':12346, EmployeeName:'fghij',...},
  ...
]

However, the current JSON contains additional properties and the data is nested under the "Results" property. Referring to the documentation, it seems that reformatting the JSON to include a 'data' property is necessary:

{
  "draw": 1,
  "recordsTotal": 57,
  "recordsFiltered": 57,
  "data": [
    [
      "12345",
      "John Smith",
      "Adam James",
      "Manager",
    ],
    ...
}

To address this issue, consider utilizing the 'dataSrc':'Results' property in your datatable configuration as advised by Ankush for a straightforward solution.

Answer №2

To inform the datatable where to fetch data from, utilize the dataSrc attribute:

$(document).ready(function() {
    $('#example').DataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": "/api/url",
         "dataSrc": function (json) {
                   debugger;
          return json.data;
        },
        "columns": [
            { data: "EmployeeCode" },
            { data: "EmployeeName" },
            { data: "ManagerName" },
            { data: "DesignationName" }
        ],
    } );
} );

For more information on dataSrc, refer to this link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a Google map with multiple markers within a 10 km radius of the current location in a rectangular shape

Currently, I am working on a web application that utilizes Google Maps and AngularJS. One of the requirements is to display multiple markers on the map, but only those within a 10km range from the corners, not in a circular radius. In order to achieve th ...

Tips on keeping a div element in a fixed position until triggered by jQuery

I've managed to create a navigation bar within a header that sticks to the top of the screen once you scroll down past 100px. The functionality works well, but I'm looking to make the navigation bar stay fixed on the right until it snaps, essenti ...

leveraging the default browser behavior for the href and target attributes within an <a> element in Angular 2

How can the behavior of a simple anchor tag in Angular 2 be implemented without being overridden by the routing module? <a href="some url" target="_whatever"> It is crucial to prevent the routing module from highjacking the URL using the base href. ...

What distinguishes CLIENT_SECRET from oauth2client credentials in Google Sheets API json files?

I successfully implemented the Google Sheet Python API by following their Quickstart guide (https://developers.google.com/sheets/api/quickstart/python). Here is the code snippet that made it work: def get_credentials(): """Gets valid user credentials ...

Only display the parent component in React if there are children components that will be rendered

Navigating this situation in React has me puzzled. Within a group of tabs, I have several chart components that render based on their permission prop. If the user lacks access to a chart, it won't be displayed - straightforward enough. However, I&ap ...

When attempting to upload a file from IOS10.3.1, the server received the correct file size but retrieved incorrect data, all of which appeared as

I'm facing issues with correctly uploading files. Our iOS and Android app allow users to select a local image file and upload it to our Nginx server. Issue Summary: Approximately 5% of the total upload requests result in broken image files on the se ...

Incorporating OpenLayers and TypeScript: Issue with Event.map.forEachFeatureAtPixel, where the argument type is not compatible with the parameter type

I am currently attempting to implement Open Layers v7.2.2 with TypeScript. {When not using TypeScript, the code functions properly} function OnMapClick(event: MapBrowserEvent<UIEvent>) { event.map.forEachFeatureAtPixel(event.pixel, function(curren ...

In Android Kitkat 4.4.4, the Ionic navbar displays icons vertically when using the <ion-buttons end> feature

When viewing in the browser with ionic serve, everything looks fine. However, on an Android Kitkat device running version 4.4.4, the buttons on the right side of the navbar are displaying vertically instead of horizontally. <ion-navbar> <ion-ti ...

Transmitting data from the backend to AngularJS during page load

After diving into Angular JS for the first time, I've hit a roadblock at an essential stage. My setup consists of an AngularJS front end and Grails backend. Check out the code snippets below along with my query. URL Mapping entry: as "/graph"(cont ...

Teach me how to utilize Import / require() in Static Folder

I've been attempting this task for a while, but I'm unsure how to incorporate import or require into the express static folder. When I try to use it, I receive an error stating "require not defined" which makes sense since these are not supported ...

Discover the process of creating a dynamic mailto link using AJAX and HTML

One of my tasks involves extracting email addresses from an XML document using AJAX, and then displaying them on a webpage as clickable links for sending emails. Here is a snippet of JavaScript code I am working with: emailobj = listings[i].getElementsBy ...

Error: Trying to use Router without providing a middleware function. Please make sure to pass a valid middleware function while using Router

While working on my express application with MongoJS, I encountered an issue where despite returning a function, it was showing that an object has been returned instead. To address this, I made sure to include module.exports=router in my JavaScript file. H ...

When using express and passport-local, the function `req.isAuthenticated()` will typically return a

I'm seeking some insight into my current situation. I've noticed that whenever I call req.isAuthenticated() in an app.router endpoint, running on port 3001 via the fetch API, it always returns false. It seems like the connect.sid is not being pro ...

Issues with AJAX formData functionality

I'm having difficulties with the formData in my Ajax calls. I have searched extensively for solutions and tried various approaches, including using getElementById, but nothing seems to work. The form in question has an id of add-lang-form: <form ...

Testing React Component State Updates

I've been dedicated to achieving close to 100% unit test coverage with my React application, focusing particularly on the useAsync hook. I came across a code snippet from react hooks: import { useState, useEffect, useCallback } from 'react'; ...

Concerning Java's Map and Array functionalities

When working with Javascript, we have the ability to create statements like the one below. var f_names = { 'a' : 'Apple', 'b' : 'Banana' 'c& ...

What could be causing my ng-grid footer to refuse to align with the bottom border?

Currently utilizing ng-grid and various AngularJS UI Bootstrap components on my website, I have encountered a recurring issue. By diligently investigating, I have successfully replicated the problem. Access the Plunker demonstration through this link. The ...

Whenever I execute the code, my if statement seems to interpret the conditions as true regardless of the actual values

let num = (Math.floor(Math.random() * 6 + 1)) console.log(num) if (num === 6) console.log('Wow, you hit the jackpot with a rarity of 1/6!') The above code snippet generates a random number between 1 and 6, then prints "that was a 1/6 chance" if ...

Ionic retrieves a filtered array of JSON data

Having difficulty filtering the array to retrieve values where the parent id matches the id that is provided. For instance, if an ID of 1 is sent, it should result in a new array with 3 items. An ID of 4 will return 1 item, and an ID of 5 will also return ...

Incorporating and verifying unseen reCAPTCHA

I'm looking to implement reCAPTCHA on a form. After registering, I obtained the necessary keys. <form> <input type="text" name="name" /> <input type="email" name="email" /> <textarea name="message"></textarea&g ...