0

I am trying to populate a chart with test data before using production data but I cannot get the data into the chart. I do not have any errors that I can find and the controller is returning 2 complete datasets on the return Json(_chart);. The chart displays but there is no data in the chart. What am I doing wrong here?

index.cshtml

    <head>
       <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.js"></script>
       <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
       <script type="text/javascript">
           jQuery.extend({
               getValues: function (url) {
                   var result = null;
                   $.ajax({
                       url: url,
                       type: 'get',
                       contentType: "application/json; charset=utf-8",
                       dataType: 'json',
                       async: false,
                       sucess: function (data) {
                           result = data;
                       }
                   });
                   return result;
               }
           });
       </script>  
    </head>
    
    <body>
       <canvas id="myLineChart" width="400" height="200"></canvas>

       <script type="text/javascript">
           var ctx = document.getElementById("myLineChart").getContext('2d');
           var tData = $.getValues("/Home/MultiLineChartDataEF");
           var myLineChart = new Chart(ctx, {
               type: 'line',
               data: tData
           });
       </script>
    </body>

HomeController.cs

        public JsonResult MultiLineChartDataEF()
        {
            var chartData = _context.ChartTests.ToList();
            var uniqueProducts = from d in chartData orderby d.ProductName group d by d.ProductName into m select m.Key;
            var uniqueMonths = from a in chartData orderby a.MonthNumber group a by a.Month into g select g.Key;
            string[] cols = new string[] { "#FF0000", "#000000" };
            int i = 0;
            Chart _chart = new();
            _chart.labels = uniqueMonths.ToArray();
            _chart.datasets = new List<Datasets>();
            List<Datasets> _dataSet = new();
            foreach(var d in uniqueProducts)
            {
                var colors = new string[uniqueProducts.Count()];
                for (int j = 0; j < colors.Length; j++) colors[j] = cols[i];
                _dataSet.Add(new Datasets()
                {
                    label = d,
                    data = (from a in chartData where a.ProductName == d select a.Amount).ToArray(),
                    backgroundColor = new string[] { cols[i] },
                    borderColor = new string[] { cols[i] },
                    borderWidth = "1"
                });
                i++;
            }
            _chart.datasets = _dataSet;
            return Json(_chart);
        }

Chart.cs

using System.Collections.Generic;

namespace ChartTest.Models
{
    public class Chart
    {
        public string[] labels { get; set; }
        public List<Datasets> datasets { get; set; }
    }
    public class Datasets
    {
        public string label { get; set; }
        public string[] backgroundColor { get; set; }
        public string[] borderColor { get; set; }
        public string borderWidth { get; set; }
        public string[] data { get; set; }
    }
}

ChartTest.cs

namespace ChartTest.Models
{
    public partial class ChartTest
    {
        public string ProductName { get; set; }
        public string Month { get; set; }
        public string Amount { get; set; }
        public int? MonthNumber { get; set; }
    }
}

screenshot of the empty chart

7
  • You cannot use getValues() the way you are using it. Ajax call takes some time, but result is being returned immediately. Add console.log('returning result'); just before the return line, and add another console.log('ajax success'); inside of the ajax success callback. You will see 'returning result' happens before 'ajax success'. Commented May 3, 2022 at 19:08
  • @hijinxbassist Can I resolve this by using an async function in Javascript along with fetch? Commented May 3, 2022 at 19:49
  • 1
    Personally, I would just populate the chart (or call a populate method) from inside of the success function. Since you want to reuse that function, perhaps add a callback function parameter that you call on success with the results Commented May 3, 2022 at 19:51
  • I just realized that your ajax is marked as async=false. That forces the wait you expect, but can cause huge problems. Are you sure your ajax call is producing results? Have you checked in the browser console? Commented May 3, 2022 at 20:03
  • @hijinxbassist something is wrong with the call. It is returning false (error) instead of success for some reason. I'm trying to troubleshoot it but I can't seem to find a way to display the error to either an alert or console.log. It's just showing null Commented May 3, 2022 at 20:30

1 Answer 1

1

I think it's just a spelling mistake of your ajax, the success of the Ajax call should be "success", not "sucess", after I corrected it, the data can be fetched normally.

jQuery.extend({
           getValues: function (url) {
               var result = null;
               debugger;
               $.ajax({
                   url: url,
                   type: 'get',
                   contentType: "application/json; charset=utf-8",
                   dataType: 'json',
                   async: false,
                   success: function (data) {
                       result=data;
                   },
                   error:function(){
                       return error;
                   }
               });
               return result;
           }
       });

Test Result:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! jQuery and Javascript never threw an error but it works great now! It just took that 2nd set of eyes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.