Is AJAX/JSON Referencing the Way to Go?

After making good progress in using JavaScript to fill in values, I've hit a roadblock. Despite checking my references, my html table isn't displaying any output.

The goal is simple - extract values from a JSON retrieved by an API and insert them into a table. Using a double for-loop (outer loop to find the perf_data and inner loop to fetch individual values) to cycle through the JSON data, I aim to change the color based on specific conditions (e.g., if value is above 7).

This is the sample JSON file:

{
  "product" : [ {
    "name" : "TxP",
    "id" : "TxP",
    "measurement" : [ {
      "id" : "222222",
      "alias" : "Site Login",
      "perf_data" : [ {
        "name" : "last_five_minute",
        "value" : "4.908",
        "duration" : "300",
        "unit" : "seconds"
      }, {
        "name" : "last_fifteen_minute",
        "value" : "3.99",
        "duration" : "900",
        "unit" : "seconds"
      } ],
      "avail_data" : [ {
        "name" : "last_five_minute",
        "value" : "100",
        "duration" : "300",
        "unit" : "percent"
      }, {
        "name" : "last_fifteen_minute",
        "value" : "100",
        "duration" : "900",
        "unit" : "percent"
      }, {
...

The .js file involved:

var jsonData = new XMLHttpRequest();
var url = "---";

function changeColor(input, value){
if (value < 7) {
    $(input).removeClass();
    $(input).addClass('high');
    }
}

jsonData.onload = funtion() {
  if (jsonData.status === 200){
    responseObject = JSON.parse(jsonData,responseText);

    var newContent = '';

    for (var i = 0; i < responseObject.perf_data.length; i++) {
         if (measurement.id === '222222') {
            for (var x = 0; x < responseObject.value.length; x++) {
                 newContent += '<td id = "part">'+changeColor(responseObject.value[x])
                                +'</td>';
            }
            document.getElementById('content').innerHTML = newContent;
         }
    }

  }
};

jsonData.open("GET",url,true);
jsonData.send();

My query centers around whether I'm correctly utilizing the double for-loop to navigate through the JSON file? While it seems like I'm following examples of simpler JSON referencing, could there be another reason behind the error?

Appreciate your help in advance.

Answer №1

You may want to consider including additional properties in your code. While it could potentially work, the effectiveness for the specific problem at hand is uncertain without more context.

for (var i = 0; i < responseObject.product[0].measurement.length; i++) {
     if (responseObject.product[0].measurement[i].id === '222222') {
        for (var x = 0; x < responseObject.product[0].measurement[i].perf_data.length; x++) {
             newContent += '<td id = "part">'+changeColor(responseObject.product[0].measurement[i].perf_data[x].value)
                            +'</td>';
        }
        document.getElementById('content').innerHTML = newContent;
     }
}

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

Iterating through elements within the ng-content directive in Angular using *ngFor

Is it possible to iterate through specific elements in ng-content and assign a different CSS class to each element? Currently, I am passing a parameter to enumerate child elements, but I would like to achieve this without using numbers. Here is an example ...

Tips for implementing an active class for td within jQuery tabs?

I'm currently using Jquery tabs within a table, and it's working fine. However, I need to activate the td when its link is clicked. Here's my code: $(document).ready(function() { $(".vertical_tabs_menu a").click(function(event) { ...

Having difficulty displaying a partial view within a view while making an AJAX call

Trying to figure out what's missing in my code. I have a view with some radio buttons and I want to display a different partial view when a radio button is selected. Here's the snippet of my code: Controller public ActionResult Method(string va ...

Randomizer File Name Maker

I was questioning the behavior of Multer Filename. If Multer stores files with random filenames, is there a possibility of two files having the same name in Multer? In other words, if I am storing files from a large number of users, could the filenames e ...

function that accepts another function as an argument

I am trying to figure out a way to call a function from a function argument, like so: var arg = function() {/*do something*/}; function do(arg) { arg(); } do(arg); I want to be able to put multiple functions in the argument, sometimes just one functi ...

Injecting services into AngularJS controllers helps to provide the necessary dependencies

Greetings! Here is the code snippet for my service: angular.module('lucho1App').factory('ApiExample', ['$http', '$q', function($http, $q) { return { promiseToHaveData: function() { return $ht ...

Tips on simulating the Q functions during unit testing in node.js using mocha and rewire!

Struggling with an issue while writing unit tests for node.js. The original code in my file is: var Q=require('q') . . . return Q.all(promises).then(function(data) { _.each(data, function(data) { checking.pu ...

Obtaining information from an external server using JSONP

Hey there! I'm currently working on retrieving data from a web API located on an external server. When I check the Chrome debugger under Network -> Response, I can see the correct data. However, when I substitute my URL with a Flickr JSON URL, it ...

Which DocType is most suitable for my web application?

I'm grappling with the HTML and XHTML specifications, and I can't decide which one to go for. Can you help me understand which is better? For instance, if I have a web application in PHP that searches an image database and displays results dynam ...

Using Angular2 to bind one-way data to a JSON attribute

Utilizing Angular2's one-way data binding, I am attempting to bind an input field value to a specific JSON property within the following object: [ { "name": "my name", "list": [ { "date": "0101970", "list": [ ...

Using the angular function directly is not possible without using setTimeout

My goal is to maintain the functionality of the back button in our application. We have implemented a back button that, when clicked, should preserve all the values selected or filled out by the user in the form. This task is being carried out in an MVC fr ...

The Nodejs express static directory is failing to serve certain files

Hello everyone, I'm currently working on a project using NodeJs, Express, and AngularJS. I've encountered an issue where my page is unable to locate certain JavaScript and CSS files in the public static folder, resulting in a 404 error. Strangely ...

Fixing Firefox Bug: How to Eliminate Non-Numeric Characters from "Number" Input Fields

Completing this task seems straightforward. I need to eliminate any non-numeric characters from an input field specified as type "number" in Firefox when a key is pressed. The code snippet provided: $("#field").on("keyup", function() { regex = /[\& ...

Is there a way to handle the completion event of jQuery's .tmpl() method?

Can someone guide me on how to create a $.tmpl ready function? In my code, I send the ajax json to my createForm function. var doFunction = { new: function() { $.ajax({ url: 'index.php?...', success: function(data) { cr ...

React, incorporating emojis within a dropdown menu

Recently, I've been developing a small game using React where players can customize settings before beginning. The game involves four players chasing different tokens on the map while avoiding the player designated as "it". Within my code, I have a r ...

Best practices for utilizing Async/Await in Node 8: A comprehensive guide

With node version 8, async/await becomes available, making code linear for the first time in nodejs natively. This is a nice improvement. In the past, many articles claimed that functions with try/catch blocks were not optimized in the v8 javascript engi ...

Is it possible to restart an animated value in React Native?

I'm facing an issue in my react native app where I have created a simple animated progress bar, but I am unsure how to reset the animation. I attempted the following approach without success: progressValue = 0; How can I reset the animation? Also, w ...

PHP String Wrapping

I'm currently facing an issue with my code. I have a piece of code that creates an image from an external source of an image and a string. The string is retrieved using json data. The problem arises when I use the string obtained from the json data a ...

Disable timezone in my JavaScript random date generator

I have a code where I am trying to generate random dates, but the timezone is always included and I'm not sure how to remove it. Can someone assist me with this? I am new to coding, so any help would be greatly appreciated! Thank you. var startDate ...

Leveraging icons with Bootstrap 4.5

I am currently exploring how to incorporate Bootstrap 4.5 icons using CSS. Do you have any examples of code that could guide me on how to achieve this? I am specifically interested in understanding the required CSS declarations that would allow me to use t ...