Is it possible to generate two output JSON Objects for a JavaScript line chart?

How can I display two lines in a Chart.js line chart using data from a JSON file with 2 objects stored in the database?

When attempting to show both sets of data simultaneously, I encountered an issue where the output was always undefined. Why is this happening and how can I fix it?

Error:

Cannot read property 'current_week' of undefined

JSON Output:

{"current":[{"current_week":23},{"current_week":636},{"current_week":237}],"last":[{"last_week":235},{"last_week":74},{"last_week":737},{"last_week":767},{"last_week":546},{"last_week":73},{"last_week":453}]}

JS Chart.js Code:

$(document).ready(function() {
  $.ajax({
    url : "http://localhost/r6team-new/admin/includes/stats/website-weekly-stats.php",
    type : "GET",
    success : function(data) {
      console.log(data);

      var current_week = [];
      var last_week = [];

      for(var i in data) {
        current_week.push(data.current[i].current_week);
        last_week.push(data.last[i].last_week);
      }

      console.log(current_week);
      console.log(last_week);

      var visitorsChart = {
        labels: ['MO', 'DI', 'MI', 'DO', 'FR', 'SA', 'SO'],
        datasets: [{
          type                : 'line',
          data                : current_week,
          backgroundColor     : 'transparent',
          borderColor         : '#007bff',
          pointBorderColor    : '#007bff',
          pointBackgroundColor: '#007bff',
          fill                : false
        },
        {
          type                : 'line',
          data                : last_week,
          backgroundColor     : 'tansparent',
          borderColor         : '#ced4da',
          pointBorderColor    : '#ced4da',
          pointBackgroundColor: '#ced4da',
          fill                : false
        }]
      };

      var ctx = $("#visitors-chart");

      var LineGraph = new Chart(ctx, {
        data: visitorsChart,
      });
    
    },
  });
});

Answer №1

It seems there is an issue with your loop logic

var current_week = [];
var last_week = [];

for(var i in data["current_week"]) {
   current_week.push(i["current_week"]);
}

for(var i in data["last_week"]) {
   last_week.push(i["last_week"]);
}

Alternatively, you can simplify it like this

$(document).ready(function() {
  $.ajax({
    url : "http://localhost/r6team-new/admin/includes/stats/website-weekly-stats.php",
    type : "GET",
    success : function(data) {
      var visitorsChart = {
        labels: ['MO', 'DI', 'MI', 'DO', 'FR', 'SA', 'SO'],
        datasets: [{
          ...
          //current_week
          data: data["current"].map(d => d["current_week"])
        },
        {
         ...
          //last_week
          data: data["last"].map(d => d["last_week"]) 
        }]
      };

      var ctx = $("#visitors-chart");

      var LineGraph = new Chart(ctx, {
        data: visitorsChart
      });
    
    },
  });
});

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

Transferring an array from PHP to Javascript using GET method

Can someone help me figure out how to pass an array to Javascript after it sends a GET request to PHP? I've got the data sending and retrieving down pat, but now I'm stuck on how to send the data back as an array. Here's what I have so far: ...

A guide on transferring variables to sessions instead of passing them through the URL in PHP

<a class='okok' id='$file' href='" . $_SERVER['PHP_SELF'] . "?file=" . $file . "'>$file</a> The given code snippet represents a hyperlink that passes the filename to the 'file' variable, which ...

iteration using underscores in JavaScript

I am currently working on creating an object using underscore and backbone. I have an array of objects, each containing a nested object with different sets of data. Within the array, data[0] holds the name of a location while data[2] contains the coordina ...

Persistent error function arises from Ajax request in Laravel

Greetings everyone. I'm currently working on my Laravel application and trying to verify the attendance for a specific date, subject, grade in my database table. If the data exists, I have implemented an if statement to display the desired results bas ...

Challenges arise when attempting to pass array data from Ajax to Google Maps

I'm facing an issue with my Google map. I have a data array that is dynamically returned, and I want to use it to add markers to the map. However, the markers don't work when I pass the data variable to the add_markers() function. It only works i ...

Fade out all the other images using jQuery

I have created a jQuery code to fade images, but when I move the mouse over them all images fade simultaneously! $(".playThumb").fadeTo("normal", 1); $(".playThumb").hover(function() { $(".playThumb").each(function() { if ( $(this) != $(this) ...

Fetching a JSON object from an external URL using JavaScript

Currently, I am working on a project using JavaScript and have an API that provides me with a JSON Object. You can access this JSON object by clicking on the following link: . Within this JSON object, there is a specific element located at JSONOBJECT.posi ...

The issue arises when DataTable fails to retrieve the ID element following a page transition

I am facing an issue with making ajax calls on focus for each text input. I am able to do it on the first page, during document ready event. However, when I navigate to another page, JavaScript is unable to parse the inputs as they were not created during ...

Set up local npm packages for easy access by different projects

Can someone explain to me how npm works compared to Maven (I have a background in Java) when it comes to package management? I've developed a generic component using Angular 4 that will be used across multiple projects. I've published it to our n ...

Exploring the World of JSON Nested Arrays with Unknown Titles and Organizing Them for Storage

Apologies if this question has already been addressed elsewhere, but I couldn't find it. I have a JSON object with dynamic keys: { "main": [ { "Example1": [ { "Example1_Var02": "5", ...

Using Vanilla Javascript to implement a dark mode toggle button

I've been struggling with getting a button to properly switch a website to dark mode. I already have a night mode that works based on the user's location and time, so I know the issue lies within my JavaScript... Initially, I tried adding ' ...

Incorporating base Tailwind CSS colors with the daisyUI theme: A simple guide

For my NextJS project, I'm utilizing Tailwind CSS in conjunction with daisyUI. In my configuration file tailwind.config.js, I have it set up as follows: /** @type {import('tailwindcss').Config} */ /* eslint-env node */ module.exports = { ...

What is the method for accessing JSON data?

Looking for assistance on a coding issue I'm facing. I need my JavaScript code to read JSON data and grant access to a staff panel based on the information provided. Below is the sample JSON: { "User1": { "User": " ...

Spin the div in the opposite direction after being clicked for the second time

After successfully using CSS and Javascript to rotate a div by 45 degrees upon clicking, I encountered an issue when trying to rotate it back to 0 degrees with a second click. Despite my searches for a solution, the div remains unresponsive. Any suggestion ...

Adjust the initial letter of every word with JQ Capitalization

I am currently working with a large JSON file using JQ to filter out unnecessary elements. While I have successfully achieved this, I encountered an issue with certain values being all capitalized strings. Unfortunately, JQ does not provide a built-in func ...

Executing Laravel Ajax Requests on the whole website

I have been encountering an issue with my Ajax post call in my application. The call is supposed to update the Navigation throughout the entire site, but it seems to be working on some pages and not others. I am looking for a way to fix this and make it mo ...

There was an error during compilation: Module not detected - Unable to locate './xxxx'

Looking for help with importing a file from another folder into my Next.js project. I need assistance with the correct syntax and paths as I am encountering an error. Here is a link to the screenshot of the error: Below are the two files: //src/component ...

A step-by-step guide to invoking a function upon submitting a form with an external JavaScript file

How can I execute a function when the user submits a form using an external JavaScript file? index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>example</title> ...

Steps to stop POST requests sent via AJAX (acquired through Firebug)

Is there any way to protect against users spamming a post request? Consider a scenario where a form is submitted through an Ajax post. I've observed that the post request can be duplicated by simply right clicking on it and choosing "open in a new tab ...

The default action is not triggered when the click event occurs

Hey there, I have been working on this <ol> list of events using jQuery (version 1.4.2). Everything is set up within the $(document).ready() function. Something strange is happening where when I click on the <li>, it triggers a click on the co ...