简体   繁体   中英

How to properly code Javascript / Ajax for use with Chart.js

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",
                        }
                    }
                });

            }
        });
    };

});

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM