0

I have a controller action in my MVC project that creates a json record with the components needed. This is working. The issue I am having is bringing it into a chart.js canvas. This will be a pie chart that shows all the related countries with a count of each. Json has this info. Originally this was setup to use google visualization but I want to use chart.js. I just started using it. Creating charts with static data is no issue but I am pulling the info from a SQL table and creating a json to read from.

I have tried using the same structure and calling the data: data[] but it doesn't work I have also tried data: getData, which is a var for the ajax function. I am getting the data per the council on refresh.

Here is my controller Action

        public ActionResult CustomersByCountry()
    {
        CustomerEntities _context = new CustomerEntities();

        var customerByCountry = (from c in _context.Addresses
                                 group c by c.Country into g
                                 orderby g.Count() descending
                                 select new
                                 {
                                     Country = g.Key,
                                     CountCustomer = g.Count()
                                 }).ToList();

        return Json(new { result = customerByCountry }, JsonRequestBehavior.AllowGet);
    }

And here is the JavaScript/ajax - which is nested in a document.ready function with the rest of the charts.

EDIT - changed Ajax - Still not working

OrdersByCountry()

    function OrdersByCountry() {
        $.ajax({
            url: '/admin/CustomersByCountry',
            method: "GET",
            dataType: "json",
            error: function (_, err) {
                console.log(_, err)
            },
            success: function (data) {
                console.log (data);
                var customer = $("#customerByCountryPieChart").get(0).getContext("2d");
                console.log(customer)
                var cpieChart = new Chart(customer, {
                    type: 'pie',
                    data: data,
                    options: {
                        responsive: true,
                        title: {
                            display: true,
                            text: "Customers By Country",
                        }
                    }
                });
            }
        });
    };

Edit - The now working code is below.

I changed it to get states instead of country, just to clear up possible confusion. It made more sense to me to get States rather than Country at this point. This is working - meaning displaying the graph, I still need to work on the labels etc.

        OrdersByStates()

    function OrdersByStates() {

        $.ajax({
            url: '@Url.Action("CustomersByStates", "Admin")',
            data: JSON,
            contentType: "application/json; charset=utf-8",
            method: "get",
            dataType: "json",
            error: function (_, err) {
                console.log(_, err)
            },
            success: function (response) {
                console.log(response);
                var jsonresult = response

                var labels = jsonresult.result.map(function (e) {
                    return e.State;
                });
                var data = jsonresult.result.map(function (e) {
                    return e.CountCustomer;
                });;

                var ctx = document.getElementById("CustomerByStatePieChart").getContext("2d");
                var cpieChart = new Chart(ctx, {
                    type: 'pie',
                    data:
                    {
                        datasets: [
                            {
                                backgroundColor: ["#46BFBD", "#F7464A"],
                                hoverBackgroundColor: ["#5AD3D1", "#FF5A5E"],
                                label: "Orders",
                                data: data,
                            }]
                    },
                    options: {
                        responsive: true,
                        title: {
                            display: true,
                            text: "Customers By Country",
                        }
                    }
                });

            }
        });
    };

});
3
  • A great answer here: stackoverflow.com/questions/44990517/… Commented Dec 19, 2018 at 21:01
  • You cannot use getData as a value for your data, instead have instantiation of your chart inside your Ajax success using the response data as your data value Commented Dec 19, 2018 at 21:08
  • So I tried that before and didn't have any luck. I put replaced the code with the code that has the Canvas inside the ajax success. This still does not work, maybe I am missing something in there? Commented Dec 19, 2018 at 21:56

1 Answer 1

0

try:

var cpieChart = new Chart(customer, {
                   type: 'pie',
                   data: data.result,
                   options: {
                       responsive: true,
                       title: {
                           display: true,
                           text: "Customers By Country",
                       }
                   }
               });

the response from the server "data" var on your request is {result: LIST}

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

1 Comment

So this doesn't appear to work either. I did try that before I believe. also changed the success function to be just result and that didn't work either. I have other charts on this page that are static and work fine. The Text: Customers By Country does show up on the page. This is what I am getting back from the server. {"result":[{"State":"Maryland","CountCustomer":1},{"State":"Pennsylvania","CountCustomer":1}]} I changed it to state instead of country also. thanks

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.