Passing SQL results from controller to chart.js

0๐Ÿ‘

โœ…

If you want your controller to be hit you need to make an ajax request. This ajax call should be done on the action which you want the controller to be called. Button click or so on. Start using console.logs to debug your javascript.

If you want this code to be execute on page open, wrap the ajax call in document.ready function.

   $.ajax({
        type: "POST",
        url: "Home/currentPopulation",
        //data: jsonData, if you need to post some data to the controller.
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        error: OnErrorCall
    });

    function OnSuccess(response) {
        var aData = response.d;
        console.log(aData);
        //build here your **data** as object wanted by Bar. Colors which you want and so on, options could be empty object {}. I think is possible to call bar without options, you need to read the documentation.

        var ctx = $("#myChart").get(0).getContext("2d");
        var myBarChart = new Chart(ctx).Bar(data, options);
    }

    function OnErrorCall(response)
    {
        alert('error');
    }

Here I show you little example how to do it. You can just google chart.js with mvc there is a lot of examples. Check if the url is correctly written I think you should remove the / in the begging.

This is just suggestion.

Also if you had the money and this is serious chart project use highcharts.js ! This is the best library which can work totally offline and gives you really good flexibility.

Usefull links:

ChartJS documentation

Leave a comment