Home > database >  How to integrate charts with js and jQuery?
How to integrate charts with js and jQuery?

Time:12-18

I am trying to get data from an API and edit the endpoint based on the selected value from a dropdown and show the respective chart for it, can I integrate js, jQuery and charts all together? Below is my code where I tried this:

async function bruh(){
  $( document ).ready(function() {
  $('select').on('change', async function() {
    this.value = this.value.toLowerCase();
    const apiUrl = 'https://api.covidtracking.com/v1/states/' this.value '/daily.json';

  const response = await fetch(apiUrl)
  const barChatData = await response.json()
  console.log(barChatData)
  const positive = barChatData.map((x) => x.positive)
  const date = barChatData.map((x) => x.date)
  positives = positive
  dates = date
  });
})
}
async function dummyChartbruh() {
  await bruh()
  const ctx = document.getElementById('yourChart').getContext('2d');

  const chart = new Chart(ctx, {
      
      type: 'line',
  
      
      data: {
          labels: dates,
          datasets: [{
              label: 'Positive',
              backgroundColor: 'blue',
              borderColor: 'rgb(255, 99, 132)',
              data: positives,
              fill: false
          }
         
        ]
      },
  
    
      options: {
        tooltips: {
          mode: 'index'
        }
      }
  })
  document.getElementById("yourChart").removeAttribute("hidden");
  $('#yourChart').show()
}

dummyChartbruh() 

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev nYRRuWlolflfl" crossorigin="anonymous">
  <link rel="stylesheet" href="/styles.css" />
  <title>Covid Data</title>
</head>
<body>
  <div >
  <div >
  <h2>Covid Data</h2>
  <select>
    <option value="AL">Alabama</option>
    <option value="AK">Alaska</option>
    <option value="AZ">Arizona</option>
    <option value="AR">Arkansas</option>
    <option value="CA">California</option>
    <option value="CO">Colorado</option>
    <option value="CT">Connecticut</option>
    <option value="DE">Delaware</option>
    <option value="DC">District Of Columbia</option>
    <option value="FL">Florida</option>
    <option value="GA">Georgia</option>
    <option value="HI">Hawaii</option>
    <option value="ID">Idaho</option>
    <option value="IL">Illinois</option>
    <option value="IN">Indiana</option>
    <option value="IA">Iowa</option>
    <option value="KS">Kansas</option>
    <option value="KY">Kentucky</option>
    <option value="LA">Louisiana</option>
    <option value="ME">Maine</option>
    <option value="MD">Maryland</option>
    <option value="MA">Massachusetts</option>
    <option value="MI">Michigan</option>
    <option value="MN">Minnesota</option>
    <option value="MS">Mississippi</option>
    <option value="MO">Missouri</option>
    <option value="MT">Montana</option>
    <option value="NE">Nebraska</option>
    <option value="NV">Nevada</option>
    <option value="NH">New Hampshire</option>
    <option value="NJ">New Jersey</option>
    <option value="NM">New Mexico</option>
    <option value="NY">New York</option>
    <option value="NC">North Carolina</option>
    <option value="ND">North Dakota</option>
    <option value="OH">Ohio</option>
    <option value="OK">Oklahoma</option>
    <option value="OR">Oregon</option>
    <option value="PA">Pennsylvania</option>
    <option value="RI">Rhode Island</option>
    <option value="SC">South Carolina</option>
    <option value="SD">South Dakota</option>
    <option value="TN">Tennessee</option>
    <option value="TX">Texas</option>
    <option value="UT">Utah</option>
    <option value="VT">Vermont</option>
    <option value="VA">Virginia</option>
    <option value="WA">Washington</option>
    <option value="WV">West Virginia</option>
    <option value="WI">Wisconsin</option>
    <option value="WY">Wyoming</option>
</select>   

  </div>
  <canvas id="myChart" ></canvas>
  <canvas id="yourChart" hidden></canvas>
</div>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
  <script src="app.js"></script>
</body>
</html>

However it does not display any values on the chart when the dropdowns are changed, how do I correct this?

CodePudding user response:

You should assign the chart to a global variable and update its data each time a different state is selected from the drop-down. After that, you need to invoke chart.update().

For further information, please consult Updating Charts from the Chart.js documentation.

Please take a look at your amended code and see how it works.

$(document).ready(function() {
  $('select').on('change', function() {
    const state = this.value.toLowerCase();
    fetch('https://api.covidtracking.com/v1/states/'   state   '/daily.json')
      .then(response => response.json())
      .then(json => {
        myChart.data.labels = json.map((x) => x.date);
        myChart.data.datasets[0].data = json.map((x) => x.positive);        
        myChart.update();
      });
  });
});

const myChart = new Chart('myChart', {
  type: 'line',
  data: {
    labels: [],
    datasets: [{
      label: 'Positive',
      backgroundColor: 'blue',
      borderColor: 'rgb(255, 99, 132)',
      data: [],
      fill: false
    }]
  },
  options: {
    tooltips: {
      mode: 'index'
    }
  }
});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev nYRRuWlolflfl" crossorigin="anonymous">
  <link rel="stylesheet" href="/styles.css" />
  <title>Covid Data</title>
</head>

<body>
  <div >
    <div >
      <h2>Covid Data</h2>
      <select>
        <option>Select State...</option>
        <option value="AL">Alabama</option>
        <option value="AK">Alaska</option>
        <option value="AZ">Arizona</option>
        <option value="AR">Arkansas</option>
        <option value="CA">California</option>
        <option value="CO">Colorado</option>
        <option value="CT">Connecticut</option>
        <option value="DE">Delaware</option>
        <option value="DC">District Of Columbia</option>
        <option value="FL">Florida</option>
        <option value="GA">Georgia</option>
        <option value="HI">Hawaii</option>
        <option value="ID">Idaho</option>
        <option value="IL">Illinois</option>
        <option value="IN">Indiana</option>
        <option value="IA">Iowa</option>
        <option value="KS">Kansas</option>
        <option value="KY">Kentucky</option>
        <option value="LA">Louisiana</option>
        <option value="ME">Maine</option>
        <option value="MD">Maryland</option>
        <option value="MA">Massachusetts</option>
        <option value="MI">Michigan</option>
        <option value="MN">Minnesota</option>
        <option value="MS">Mississippi</option>
        <option value="MO">Missouri</option>
        <option value="MT">Montana</option>
        <option value="NE">Nebraska</option>
        <option value="NV">Nevada</option>
        <option value="NH">New Hampshire</option>
        <option value="NJ">New Jersey</option>
        <option value="NM">New Mexico</option>
        <option value="NY">New York</option>
        <option value="NC">North Carolina</option>
        <option value="ND">North Dakota</option>
        <option value="OH">Ohio</option>
        <option value="OK">Oklahoma</option>
        <option value="OR">Oregon</option>
        <option value="PA">Pennsylvania</option>
        <option value="RI">Rhode Island</option>
        <option value="SC">South Carolina</option>
        <option value="SD">South Dakota</option>
        <option value="TN">Tennessee</option>
        <option value="TX">Texas</option>
        <option value="UT">Utah</option>
        <option value="VT">Vermont</option>
        <option value="VA">Virginia</option>
        <option value="WA">Washington</option>
        <option value="WV">West Virginia</option>
        <option value="WI">Wisconsin</option>
        <option value="WY">Wyoming</option>
      </select>
    </div>
    <canvas id="myChart"></canvas>
  </div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.2/chart.min.js"></script>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
  <script src="app.js"></script>
</body>

</html>

  • Related