Having trouble connecting JSON data to TreeTable Js through knockout.js?

I found a helpful plugin called TreeTable that I am using. You can check it out here:

<table id="example-basic">
    <thead>
        <tr>
            <th>Name</th> <th>Status</th> <th>id</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: TreeView">
        <tr data-bind="attr: { 'data-tt-id': id ,'data-tt-parent-id': Parentid}">
            <td data-bind="text: Name"></td>
            <td data-bind="text: Status"></td>
            <td data-bind="text: id"></td>
        </tr>

    </tbody>
</table>
 <button type="button" name="test" onclick="test()"></button>

When I hardcode the content, it displays perfectly as a TreeView.

ko.applyBindings({ TreeView: [{ "id": "1", "Parentid": null, "Name": "test1", "Status": "OK" }, { "id": "2", "Parentid": 1, "Name": "test2", "Status": "OK" }] })

However, when I retrieve data from the server and bind dynamically, I encounter an error:

A JSON parsing error occurs with this code:
str = '[{ "id": "1", "Parentid": null, "Name": "parent1", "Status": "OK" }, { "id": "2", "Parentid": 1, "Name": "child1", "Status": "OK" }]',
json = JSON.stringify(eval("(" + str + ")")),
ko.applyBindings({ TreeView: json})

 function reload() {
 str = '[{ "id": "1", "Parentid": null, "Name": "parent1", "Status": "OK" }]'
 json = JSON.parse(str),
ko.applyBindings({ TreeView: json})

If anyone could offer assistance on how to resolve this issue, I would greatly appreciate it. Thank you! The solution to the previous error was converting the returned JSON object to a string and then parsing it. New problem: I want to dynamically reload data from the server either by clicking a button or making an AJAX call every 5 seconds, but the data ends up duplicated.

Answer №1

It's important to remember that instead of stringifying JSON and using eval(), you should be parsing it with JSON.parse(). This will help ensure your code is safe and efficient.

var data = '[{ "id": "1", "Parentid": null, "Name": "parent1", "Status": "OK" }, { "id": "2", "Parentid": 1, "Name": "child1", "Status": "OK" }]';
var jsonData = JSON.parse(data);
updateTreeView({ TreeData: jsonData });

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

retrieving data from a php file using ajax for a post request

Utilizing ajax, I have invoked the page search.php: function search(){ var title=$("#search").val(); if(title!=""){ $.ajax({ type:"post", url:"sear ...

Unable to prevent ordered lists from overlapping with other content I attempt to place beneath them in HTML

function filterImages() { let input = document.getElementById('searchbar').value; input = input.toLowerCase(); let images = document.getElementsByClassName('gallery'); for (let i = 0; i < images.length; i++) { ...

I'm confused, I installed the module but it's still showing an error message saying it can

I've been working on coding a discord music bot, and here is the code I have so far: const config = require('config.json') const Discord = require('discord.js'); const ffmpeg = require('ffmpeg-extra') const client = new ...

jspm is having trouble locating the globalResources for a 'feature' plugin in an Aurelia application

Looking for guidance on setting up and utilizing a feature plugin with Aurelia docs? Find detailed instructions at I encountered an issue where paths to resources were being transformed by jspm or Aurelia. Upon specifying the current path as .aurelia.use. ...

Tips for eliminating , , and characters from a json format

Currently, I am in the process of creating a JSON file using jq and here is the generated output: { "temperature":"21", "humidity":"12.3", "message":"Today ID 342 is running" } { "temperature":"13", "humidity":"40.1", "message":"Toda ...

Having trouble with jQuery AJAX POST JSON errors while sending special characters like "?" or "&" to the server?

I have scoured the internet for a resolution to this issue, but have come up empty-handed. Here is my jQuery code: function fetchMsg (type, msg, msgid) { $.ajax({ type: "POST", url: "fetchmsg.php", data: "type=" + type + " ...

Browsing across pages seamlessly without the need to refresh the browser

I need help with making my admin panel built using Bootstrap and integrated with Laravel navigate through tabs without refreshing the browser. Can anyone provide guidance on how to modify the code to achieve this functionality? You can check out the admin ...

Is there a table that allows users to input percentages?

Looking for help with a table that has 2 columns: "Activities" and "Average % of Time". Users need to input a % value for each activity in the "Average % of Time" column. There are 7 rows for activities. The goal is to ensure that the sum of the % values f ...

Enhancing List Page Functionality with AngularJS/MVC5 Search Feature

As I work on enhancing the List page, my main focus is on implementing a search feature. While the code below effectively displays data in a list format, I am uncertain about how to start incorporating a search functionality into this page. HTML: <bo ...

Loop through page.evaluate in Nodejs

Currently, I am attempting to utilize the for-of looping method in order to iterate through an array of URLs and apply them with the page.evaluate function from the puppeteer library. To simplify my process, I will share a snippet of my code (with a sing ...

Could there be an issue with the couch-nano changesReader batching, or am I overlooking something important?

This particular issue is related to the changesReader API within the couchdb-nano library. Expected Outcome In theory, the code below should wait for 10 seconds before returning a batch of messages from the most recent position in the changes feed. For in ...

Achieving two-way data binding using a Service in AngularJS - Step by step guide

Searching a JSON file, extracting data to create a table, and continuously monitoring for updates to display in real-time is a challenging task. Despite multiple attempts with AngularJS, achieving this has been elusive. Below is the code snippet: app.js ...

Unable to retrieve data from Material UI DatePicker

As a newcomer to React, I'm currently working on creating a reusable date input component. However, I'm facing difficulties in retrieving the values from the component to the register. Here's a snippet of my form code: import React, { useSta ...

Is it better to handle XML and JSON parsing separately or convert one format to the other before processing?

When gathering data from different web services, I encounter a mix of XML and JSON formats. My research led me to consider using JSON.Net for parsing JSON data, particularly due to its compatibility with Linq for extracting necessary items. The question a ...

Separate a tab delimited text file and store it into an array using JavaScript

Looking to parse a text file with tab-separated values in JavaScript and add them to an array? Here's how you can achieve this while excluding the header: Id Symbol 1 A 2 B 3 C 4 D 5 E 6 F 7 G This is what I have attempted so far: va ...

Making changes to a variable or option through the props in a different file

In the index.js file, I have implemented getStaticProps() to fetch data from an exported function. This function requires 2 parameters, one for the type of listing and the quantity. export async function getStaticProps() { const type = 0 const data = a ...

Mac JSON Shell Scripting

Below is the code I am struggling with: function poke() { json="curl -s -X GET http://pokeapi.co/api/v2/type/bug.json"; prop="half_damage_to" temp=echo $json | sed 's/\\\\\//\//g' | sed 's/[{}]//g& ...

Conditional radio button disabling in Material-ui

Currently, I am developing a React application using material-ui. My goal is to disable all radio buttons within a RadioGroup when a specific event occurs, and then re-enable them once the event is no longer active. For example, when a button is clicked, ...

Python script to send a Delete Request to a REST API deployed on Google App Engine

Having spent some time searching, I have identified a couple of approaches for making an API call that necessitates the use of the Delete method. First Attempt: (httplib library) url = '/v1/users/'+ spotify_user_id +'/playlists/'+ ...

Creating customized JavaScript using jQuery for Drupal 7 Form API

Currently, I am working on developing a custom form using Drupal 7 with form API and a tableselect that includes checkboxes. I have some specific constraints for selecting the checkboxes that I intend to implement using jQuery. I created a function for han ...