Utilizing JSON data in JavaScript to populate a datatable

After receiving a JSON result from an AJAX jQuery call, I stored it in a variable and attempted to insert the JSON data into a datatable. However, instead of inserting the data from the variable as intended, the datatable is currently populated with JSON data from a URL.

Despite my efforts to update the variable value with the JSON data stored in 'myjson', the operation still failed. The following is a snippet of my code:

JavaScript

<script>
    var myTable = $('#my_logs').DataTable({
        "paging": true,
        ... // data table setup parameters
    });

    $(document).ready(function() {
        $("#search").click(function() {
            var start_date = $('#start_date').val();
            var end_date = $('#end_date').val();

            if (startDate != '' && endDate != '') {
                var startDate = new Date(start_date);
                var endDate = new Date(end_date);
                let url = 'http://localhost/APICI/index.php/api/cektable';
                    fetch(url)
                    .then(res => res.json())
                    .then((out) => {
                        var resultProductData = out.filter(function(a) {
                            // date filter logic
                        });
                        console.log(resultProductData);
                        $.ajax({
                            url: 'http://localhost/APICI/index.php/api/cektablee',
                            ... // ajax request details
                        });
                    })
                .catch(err => { throw err });
            }
            else {
                alert("Both Date is Required");
            }
        });
    });
</script>

Although I want the datatable to display values from the JSON data saved in the variable resultProductData, it currently shows data fetched from this URL through an AJAX call.

The JSON data stored in the variable resultProductData can be viewed here. Whereas, the data visible in the datatable originates from this URL.

Answer №1

If you need assistance, try this:

After testing, the data is being added correctly. Please reach out if there are any queries.

<!-- Custom CSS -->
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/custom_styles/1.2.3/css/style.css">
<link rel="stylesheet" type="text/css" href=" https://cdn.customsite.net/1.5.7/css/customdatatables.min.css">


<!-- jQuery Library -->
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.5.1.min.js"></script>

<!-- Custom DataTables Script -->
<script type="text/javascript" charset="utf8" src="https://cdn.customsite.net/1.5.7/js/customdatatables.min.js"></script>

<html>
<body>
    <div class="container">
        <table id="my_logs" class="table table-striped table-bordered" style="width:100%">
            <thead>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div> 
</body>

<script type="text/javascript">
$(document).ready(function () {
 
 var myTable = $('#my_logs').DataTable({
        "paging": true,
        "lengthChange": true,
        "searching": true,
        "ordering": true,
        "info": true,
        "autoWidth": true,
        "data": [],
        "columns": [{
            "title": "Date",
            "data": "log_time"
        }, {
            "title": "User Name",
            "data": "user_name"
        }, {
            "title": "Class",
            "data": "class_name"
        }, {
            "title": "Function",
            "data": "class_function"
        }, {
            "title": "Action",
            "data": "action_title"
        }, {
            "title": "Description",
            "data": "action_description"
        }]
    });
    
    var logs = [{ "log_time": "2022-09-15", "user_name": "JohnDoe", "class_name": "login", "class_function": "authentication", "action_title": "User login", "action_description": "Logged into the system" }];
    myTable.clear();
    $.each(logs, function(index, value) {
        myTable.row.add(value);
    });
    myTable.draw();

});
</script>

</html>

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

Javascript Parameter

Each time I enter scroll(0,10,200,10); into my code, it seems to output the strings "xxpos" or "yypos" instead of the actual values. I attempted to remove the apostrophes around them, but unfortunately, that did not resolve the issue. scroll = function( ...

iisnode ran into a problem while handling the request. Error code: 0x6d HTTP status code: 500 HTTP subStatus code: 1013

Currently, I am working on a web application using ReactJS for the frontend and Express for the backend. My deployment platform is Azure. In order to verify that my requests are being processed correctly, I decided to conduct two API tests. The first tes ...

Receiving a blank array upon calling res.json() in Node.js script

I'm facing an issue with my code snippet that displays all posts, including the username and display picture of each user. Everything seems to be working fine as the log output is perfect. However, I'm struggling to return this data as a JSON obj ...

Formatting specific elements within an array

I am working with an array of names, some of which are repeated. These names are then split in half and displayed as li. One thing I am struggling to figure out is how to style the name Joeyc with text-decoration: line-through; on all instances of .book w ...

"Deploying code to Heroku using Node.js: A guide to adding git commits directly on

Currently, as I delve into learning Node and Git, I'm faced with a dilemma involving my Heroku app. The app is designed to interact with a local file on the server that serves as a basic JSON database. The issue arises when I attempt to manage this f ...

Is there a way to generate output exclusively using a POST method?

Is there a way to display the following information without using render_template and only with the method ['POST']? { username = admin email = admin@localhost id=42 } Note: It is already functioning correctly with ['GET'] ...

Version 5.3 of Laravel combined with Vue 2

Working with Vue 2 in a fresh Laravel 5.3 project, I'm faced with a challenge regarding binding a URL in the Laravel format. I've extracted some configuration rows from a database and my goal is to iterate over them to display the data, followed ...

Is JQuery function running on its own or triggered by an event without manual input?

When visitors come to my website, I want them to see two options: one for registration and the other for logging in. To achieve this, I've created two buttons and a function that makes the form/input fields fade in when clicked. However, the issue is ...

React and Material-UI issue: Unable to remove component as reference from (...)

My React components are built using Material-UI: Everything is running smoothly MainView.js import React, { Component } from 'react'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import { List, ListItem } from ...

Using radio buttons and a price slider, a unique jQuery filter for products can be

I have successfully implemented basic functionality to filter products based on price (slider) and radio boxes. However, the current filter system uses OR logic, but I need it to use AND instead. For instance, I want to find a product that is from Brand1, ...

Vue-ctl project creation halted by operating system rejection

While working on a Vue-CLI project, I encountered an issue. Has anyone else faced this problem before? Operating system: Windows 10 - Command Prompt (admin rights) @vue-cli version: 4.5.4 npm version: 6.14.6 Here is the command I ran: vue create font_ ...

Is the div empty? Maybe jQuery knows the answer

I currently have a <div id="slideshow"> element on my website. This div is fully populated in the index.php file, but empty in all other pages (since it's a Joomla module). When the div is full, everything works fine. However, when it's emp ...

Having difficulty displaying Laravel API data with Relationship in Vue Js

Working on a project that involves Laravel 10 API and Vue.js 3 frontend In my EmployeeController.php file, I have three models: Employee, Title, and Salary. The Employee model has a many-to-many relationship with the Salary and Title models, while the Sal ...

Unexpected behavior: Azure Worker Role serving XML instead of JSON

I've been reading a blog post by Brady Gaster on creating an Azure worker role to set up a JSON endpoint. Everything is going smoothly, I created the worker role and deployed it to Azure without any issues, but it's returning XML instead of JSON ...

Ways to retrieve JSON information and incorporate it into an if statement in this specific scenario

Here is the AJAX function code I have written: $('#request_form').submit(function(e) { var form = $(this); var formdata = false; if (window.FormData) { formdata = new FormData(form[0]); } var formAction = form.attr( ...

Tips for effectively wrapping Material UI v5 component to ensure the Grow component functions correctly

Being a newcomer to React, I want to apologize in advance for any silly mistakes or inaccuracies that may be present. I have successfully implemented the code for my Blog page: export default function Blog() { const [photos, setPhotos] = useState([]); ...

What separates name="" from :name=""?

If the :name="name" syntax is used, the value of the name attribute will be the unique data it receives from the props. However, if I use name="name" without the preceding :, then it will simply be "name". What role does the : play in the name attribute? ...

How to send a JavaScript variable to Flask and trigger an AJAX reload action

Introduction: I have explored similar inquiries and attempted to apply relevant code/concepts but without success. -https://stackoverflow.com/questions/43645790/passing-javascript-variable-to-python-flask -https://stackoverflow.com/questions/10313001/is- ...

Sending a JSON API call response from Go language to a next.js frontend

The issue I'm encountering: Error: Error serializing `.username` returned from `getServerSideProps` in "/". Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value. While my backend Go code functions properly ...

I'm looking to convert a particular segment of a JSON file into a Python list

This is my JSON code: { "usernames" : [ { "username":"testuser1", "name":"User1", "code":"50", "schoolcode":"100", "password":"abc ...