Retrieving data from JSON in JavaScript

Extracting data from a JSON file and using a JavaScript script to visualize it through a graph.

JSON file link:

https://i.sstatic.net/1gqov.png

The JavaScript code responsible for drawing the graph is as follows:

$(document).ready(function(){
  google.charts.load('current', {'packages': ['corechart']});
  //alert('aa00'~
  $('.error').hide();
  $(".buttonSala").click(function() {
    // validate and process form here
    $('.error').hide();
    var canal = $("#canalSala option:selected").val();
    var datai = $("#datainisala").val(); 
    var dataf = $("#datafimsala").val(); 

    //alert(canal);
    // Send the data using post
    var posting = $.post( "getTop.php", { canal: canal, dataini: datai, datafim: dataf } );

    // Put the results in a div
    posting.done(
      function(data) {
        // Set a callback to run when the Google Visualization API is loaded.

        var jsonData = JSON.parse(data).channels[canal].values;
        google.charts.setOnLoadCallback(function() {
          var dataArray = [["ts", 'values']];

          for (var i = 0; i < jsonData.length; i++) {
            var tempArray = [jsonData[i].ts, parseFloat(jsonData[i].value.replace(",", "."))];
            dataArray.push(tempArray);
          }

          // Create our data table out of JSON data loaded from server.
          var data = google.visualization.arrayToDataTable(
            dataArray
          );

          var options = {
            hAxis: {title: "Date/Time", titleTextStyle: {color: "#333"}},
            vAxis: {title: "Temperature", titleTextStyle: {color: "#333"}}
          };

          // Instantiate and draw our chart, passing in some options.
          var chart = new google.visualization.AreaChart(document.getElementById('chart_divsala'));
          chart.draw(data, options);
        });
      });
    return false;
  });
});

The correct visualization of the graph can be seen in the following link:

https://i.sstatic.net/NgJZu.jpg

Regarding this segment of the code:

var dataArray = [['ts', 'values']];

The timestamp data is used to generate the X-axis values while the "Values" label represents the Y-axis. How can I access the "chname" property from the JSON to display the relevant information on the graph, like "oxygen (%) inside wooden pipe 4"?

I've attempted various methods but have yet to achieve the desired outcome...

Answer №1

To access the json property chname, use

response.channels[canal].info.chname
. In this case, obj represents the entire object retrieved from the json file.

Therefore, update these lines:

var jsonData = JSON.parse(data).channels[canal].values;
google.charts.setOnLoadCallback(function() {
    var dataArray = [["ts", 'values']];

to this:

var response = JSON.parse(data);
var jsonData = response.channels[canal].values;
var desciption = response.channels[canal].info.chname;
google.charts.setOnLoadCallback(function() {
    dataArray = [["ts", desciption ]];

Answer №2

When ajax is used with the dataType set to JSON, the returned data is transformed into an object. To retrieve the data upon a successful request, the success function can be added as shown in the example below:

$.ajax({
  url: "getData.php",
  type: 'GET',
  dataType : "json",
  success: function (data) {
    data.forEach(function(object){
      // Add your code logic here

    });
  }
});

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

React - Updating the Color of a Specific Div within a Map Component

Currently, I am delving into React and Material UI and facing an issue with changing the background color of a clicked div. As it stands, all the divs are being affected when one is clicked. My goal is to have the background color transition from white to ...

Using numerous textures for a single mesh in THREE.js

I am working with an OBJ file that utilizes four textures. The UV coordinates in the file range from (0, 0) to (2, 2), where (0.5, 0.5) corresponds to a coordinate in the first texture, (0.5, 1.5) is a UV coordinate in the second texture, (1.5, 0.5) repres ...

What is the process for eliminating the invocation of a function in Jquery?

I am currently facing an issue with my application. When I launch the Ficha() function, it initiates an ajax call and works perfectly fine. However, another ajax call is made later to load HTML tags that also need to invoke the Ficha() function. The prob ...

Looking to retrieve the value of an input element within an ng-select in Angular 6?

Currently, I am working on a project where I aim to develop a customized feature in ng-select. This feature will enable the text entered in ng-select to be appended to the binding item and included as part of the multiselect function. If you want to see a ...

JSON Serializer for SignalR Client Side

Here is my code snippet containing multiple classes and interfaces: class A : ISomething{} Class B : ISomething{} interface ISomething{} Class C { public ISomething _member {get;set}} I am attempting to send an object from my .NET SignalR client to my ...

Tips on extracting data from an API using jQuery

Struggling with parsing data and feeling a bit stuck. That's why I'm reaching out for assistance. This is where I need help: How do I specifically retrieve market_cap values? Each value needs to be accessed individually for a specific string I ...

Information regarding gender vanishes upon refreshing the page

When the page is refreshed, the variable called jso disappears. Is there an alternative method for storing information that does not involve using a button? The goal is to have it work seamlessly when the page is reloaded without requiring any user action. ...

What is the process for sending JavaScript with an Ajax request?

Working with ajax and javascript for the first time, I'm no expert in web development. Here is the code I've written and tested so far. I have a select div containing some options. <select id="month" onchange="refreshGraph()"> When an op ...

Strategies for optimizing progressive enhancement

Designing a website that is accessible to everyone is truly an art form, and Progressive Enhancement is something I hold dear... I am curious to hear about the best techniques you have used to ensure websites work for all users, regardless of their browse ...

Sending Laravel ajax request with ID before selection of options

I am attempting to create a search function using 4 dropdown menus, where each subsequent menu loads data based on the item selected in the previous dropdown. Approach field = Dropdown option Field 1: select A Field 2: options B, C (Select B) Field 3: ...

React state not being updated by setState method

Here's the situation: let total = newDealersDeckTotal.reduce(function(a, b) { return a + b; }, 0); console.log(total, 'tittal'); //displays correct total setTimeout(() => { this.setState({ dealersOverallTotal: total }); }, 10); cons ...

How to use JQuery UI sortable to automatically scroll to the bottom of the page

Having trouble with a few sortable tables and here is how I initialized the sortable object: var options = { helper: customHelper, handle: ".moveTargetDeliverables", containment: "#fieldset_deliverables_summary", tolerance: 'pointer&a ...

Is there a way to restrict the amount of user input that is allowed?

Is it possible to restrict the input quantity when using the built-in arrow icon in the text field, but not when typing manually? <TextField variant="outlined" label="Quantity" onChange={(e) => setItemName({...i ...

jQuery wrapAll issue

I have a repeating group of three divs in my code that I need to wrap together. Here's an example from my HTML: <div class="one" /> <div class="two" /> <div class="three" /> <div class="one" /> <div class="two" /> <d ...

Generating HTML elements on the server-side vs. retrieving data as JSON and dynamically creating elements using JavaScript

Looking to implement an AJAX search feature that will retrieve and display topics from a forum, including just the topic link and subject. My question is: Which method would be more efficient and quicker? Retrieve the threads list as a JSON string, co ...

Numerous references embedded within a Vue.js component

I am currently working with multiple instances of a polygonCrop component in Vue.js, each one having a unique reference to a canvas property. These components are utilized in separate crop functions triggered by button clicks. My question is how to effecti ...

Combining element.scrollIntoView and scroll listener for smooth scrolling by using JavaScript

Can element.scrollIntoView and a "scroll" event listener be used simultaneously? I'm trying to create code that checks if the user has scrolled past a certain element, and if so, automatically scrolls smoothly to the next section. I attempted to achi ...

Using the map function with a React onClick handler

After tirelessly scouring the internet for answers to my query, I've hit a dead end. My goal is to implement a basic react click handler on my button, but for some reason, it just won't cooperate. It's likely something incredibly straightfor ...

The useAutocomplete function in Material-UI fails to consider the disabled

Currently, I am working on developing my own Autocomplete component by utilizing the useAutocomplete hook from the mui/base package. Most parts of the implementation are functioning correctly, except for the disabled option. My expectation is that the com ...

The functionality of Nuxt's asyncData is restricted when attempting to access data from authorized express routes

Setting up an online store. I began with the products, which can be pulled without authorization but require it for editing. The process is smooth so far, probably because it's happening on the client side where authentication information is included ...