Is there a way to showcase array data on a datatable by utilizing Ajax?

I am currently utilizing a MongoDB database to store some important data. I am now looking to showcase this data on an HTML Datatable.

The data that I am attempting to utilize is organized in arrays, and here is its structure:

data: [[1848, 84857], [4944, 4949], [34, 65], [3566, 78], .... ]

$(document).ready(function() {

    var table = $('#mytable').DataTable({
        "serverSide": true,
        "ajax": "/endpoint/?format=datatables",
        "columns": [

            {"data": 'data'},

        ]
    });
    setInterval( function () {
    table.ajax.reload();
}, 10000 );
});

However, the issue with my current code is that it displays the datatable in the following format:

    DATA:
[[1848, 84857], [4944, 4949], [34, 65], [3566, 78], .... ]

Whereas, I wish for it to appear as follows:

    DATA:
1848, 84857
4944, 949
36, 65 and so forth

How can I go about resolving this problem? I was contemplating using a for loop, but I am unsure how to do that since I am directly calling the data within the table variable.

The JSON response typically looks something like this:

{"data":"[[11756.53, 2.419583] .....

Answer №1

To efficiently utilize your array of array data, simply assign index key values to map your columns:

"columns": [
          {"data":0},
          {"data":1}
        ]

Check out this amazing example:

function generateRandomNumber(min, max) { // including both min and max 
  return Math.floor(Math.random() * (max - min + 1) + min);
}
$.mockjax({
    url: "/endpoint/?format=datatables",
    response: function(settings) {
      this.responseText = {
        "draw": settings.data.draw,
        "recordsTotal": 4,
        "recordsFiltered": 4,
        "data": [
          [generateRandomNumber(400, 8000), 84857], 
          [4944, 4949], 
          [34, 65], 
          [3566, 78]
        ]
      }
    }
});
var editable=false;
$(document).ready(function() {
    var table = $('#mytable').DataTable({
        "serverSide": true,
        "ajax": "/endpoint/?format=datatables",
        "columns": [
          {"data":0},
          {"data":1}
        ]
    });
    setInterval( function () {
    table.ajax.reload();
}, 10000 );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/1.6.2/jquery.mockjax.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />

<table id="mytable" class="display nowrap" width="100%">
        <thead>
          <tr>
            <th>Col1</th>
            <th>Col2</th>
          </tr>
        </thead>

        <tfoot>
          <tr>
            <th>Col1</th>
            <th>Col2</th>
          </tr>
        </tfoot>
      </table>

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

Navigating through embedded arrays in Angular

JSON Object const users = [{ "name":"Mark", "age":30, "isActive" : true, "cars":{ Owned : ["Ford", "BMW", "Fiat"], Rented : ["Ford", "BMW", "Fiat" ...

Creating a self-chaining function in JavaScript: A guide

Currently, my goal is to create an Array.prototype function called union( array_to_union ), and then utilize it in the following manner: var a = [1,2,3]; a.union([2,3,4]).union([1,3,4]) ...... I am aiming for the outcome to be the union of these arrays. ...

import external script in the head using requirejs

Here is my unique HTML structure: <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta charset="utf-8"> <title>vente-privee.com</title> <script src="@Url.Content("~/Scripts/Modules/lib/j ...

Difficulty with the increment of my counter when using addeventlistener

I'm currently facing a challenge that I can't seem to figure out... Here is the issue (in JavaScript): export default { name: "TodoList", data() { return { title: "", content: null, isDone: true, count: 0, n ...

Bootstrap Carousel with descriptions in a separate container without any display or hiding transitions

I have created a slider using Bootstrap and some JavaScript code that I modified from various sources. Everything is working well, but I want to remove the transition or animation that occurs when the caption changes. Currently, the captions seem to slide ...

Retrieving Json data results in a boolean outcome

I am working on a code snippet that includes a switch statement which returns true or false, as well as an if and else statement for further validation. The goal is to send a value through an input field using ajax and have PHP return true or false based o ...

Is it possible for npm to assist in determining the appropriate version of Primeng that is compatible with Angular 16 dependencies

While trying to add primeng to my project, I ran into an error message: npm i primeng npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

Choosing the default checkbox option as selected in a ReactJS application

Is there a way to preselect checkboxes in ReactJS based on certain output data? For example, I have the following output: {permission:{group:["can_view"],"topGroup":["can_update"]}} . After sending this data to the database and receiving back the edited ...

Adding a detached element under certain conditions

When attempting to add a detached span based on a specific condition, I encountered the following situation. const arrow = d3 .create('span') .classed('arrow', true) .text('\u2192'); //d3.select('bod ...

"Production environment encounters issues with react helper imports, whereas development environment has no trouble with

I have a JavaScript file named "globalHelper.js" which looks like this: exports.myMethod = (data) => { // method implementation here } exports.myOtherMethod = () => { ... } and so forth... When I want to use my Helper in other files, I import it ...

Creating elements in Polymer 2.0 is a breeze. Simply use the `createElement` method, then seamlessly import it using `Polymer

While working on a project, I encountered an issue where I was creating and importing an element while setting attributes with data. The code should only execute if the element hasn't been imported or created previously. However, each time I called th ...

Issue with toggling options in q-option-group (Vue3/Quasar) when using @update:model-value

I'm a newcomer to the world of Quasar Framework and Vue.js. I recently tried implementing the q-option-group component in my simple application but encountered an issue where the model-value and @update:model-value did not toggle between options as ex ...

Numerous status buttons with a variety of background colors

There are 3 buttons on the order page: [New Order], [Processing], and [Completed]. When the processing button is clicked, the background of the button should change and the order status will be updated in the database. The [New Order] button will have a ...

Using Mongoose to insert a JavaScript object directly into the database

Recently, I've been working on POSTing a JS object through AJAX to the nodejs backend. My goal is to seamlessly insert this js object into my mongoose db without having to manually map each key to the schema. This is what I have currently (a bit clun ...

Using Javascript to dynamically enable or disable an input field depending on the choice made in another field

I attempted to implement the solution provided in this answer for my code: How do I disable input field when certain select list value is picked but unfortunately, it is not working as expected. The scenario involves an HTML select field with the ID &apos ...

What is the best way to create router links on the fly in Vue.js?

I am currently exploring how to achieve the following in Vue.js <table> <tr v-for="item in messages"> <td><router-link to="'/user/' + item.id">{{ item.name }}</router-link></td> </tr> < ...

Integrate with GraphQL API using Express.js

I am facing an issue with connecting to an external API (GraphQL) on Express.js. Can anyone recommend some good tutorials on this topic? Additionally, I encountered the following error: Error message link - image Is it feasible to establish a connection ...

Having trouble accessing the scrollHeight property of null when using Selenium WebDriver

I am currently working on a function in my code that is responsible for scrolling the page. This particular function was inspired by code used to scrape Google Jobs, which can be found here. However, I encountered an error that reads "javascript error: Ca ...

Cancel submission via AJAX

I have created an ajax search filter that triggers when a specific input field has a value (in this case, it is the search query box): $("#filter").keyup(function(event){ var query = document.getElementById('query').value; if(query!=""){ $( ...

Storing user input from a dynamic form into a database using Kendo UI

I've successfully populated dynamic input form fields. However, I'm unsure how to save the data into a database using a put/post API since I have only used a get API so far. HTML code <div id="renderform" class="form horizontal-for ...