not able to pass array in chart js with ajax

Viewed 38

I have some trouble when trying to display dynamically fetched data in my bar chart using chartjs , the passed array variable can't display properly the data and keep showing nothing enter image description here

I tried by manually entering all the enteries in labels and data and it works. Can anyone suggest how to pass the array data properly? Any ideas how to solve these?

**Here is my JS code **

const ctxOne = document.querySelector('#myChartOne');
let categoryName = new Array();
$.ajax({
   url : "../controllers/getCategoryNames.php",
   method :"GET",
   success: function(data){
      let categoryData = JSON.parse(data);
      for(let i in categoryData){
         categoryName.push(categoryData[i].category_name);
      }
     
   }

})
// get the budget percent used for this month
var usedBudgetTmonth = new Array();
var usedBudgetLmonth = new Array();
$.ajax({
   url : "../controllers/budgetUsedTmonth.php",
   method :"GET",
   success: function(data){
      let budgetData = JSON.parse(data);
      categoryName.map((elt)=>{
         for(let i in budgetData){
            if(budgetData[i].category_name === elt){
               usedBudgetTmonth.push(budgetData[i].pct)
            }else{
               usedBudgetTmonth.push(0);
            }
         }
      })    
   }

})
// last month
$.ajax({
   url : "../controllers/budgetUsedLmonth.php",
   method :"GET",
   success: function(data){
      let budgetData = JSON.parse(data);
      categoryName.map((elt)=>{
         for(let i in budgetData){
            if(budgetData[i].category_name === elt){
               usedBudgetLmonth.push(budgetData[i].pct)
            }else{
               usedBudgetLmonth.push(0);
            }
            
         }
      })    
   }

})
var chartData = {
   labels : categoryName,
   datasets : [
      {
      label: 'This Month',
      data: usedBudgetTmonth,
      backgroundColor: 'rgba(255, 99, 132, 0.2)',
      borderColor:  'rgba(255, 99, 132, 1)',
      borderWidth: 1
  }, 
  {
   label: 'Last Month',
   data: usedBudgetLmonth,
   backgroundColor:'rgba(54, 162, 235, 0.2)',
   borderColor: 'rgba(54, 162, 235, 1)',
   borderWidth: 1
}]
}

const myChartOne = new Chart(ctxOne, {
   type: 'bar',
   data : chartData
});
1 Answers

You are using async code but expecting it to work like sync code. When you call new Chart all the arrays are still empty. So you will need to adjust the chart directly in your ajax and not the original variables or create the chart in your ajax

$.ajax({
   url : "../controllers/getCategoryNames.php",
   method :"GET",
   success: function(data){
      let categoryData = JSON.parse(data);
      for(let i in categoryData){
         myChartOne.data.labels.push(categoryData[i].category_name);
      }
      myChartOne.update();
   }
})
Related