Chartjs-Constant updating of x- and y-axis using a C# function to update a Chart.js chart in ASP.NET core Web Application Razor Pages

0👍

I think, after a quick glance, and if the C# code is correct, you just would have to add a call to the chart update function, in the pushData function (link to the documentation).

Update: AND fix atleast all bugs listed below (I didn’t check the C# code, there might be some there also).

    function pushData(xData, yData) {
        chart.config.data.datasets.forEach(function (dataset) {
            dataset.data.push({ x: xData, y: yData });
        });
        chart.update();
    }

But I strongly recommend checking the browser console, since your javascript code seems to have some/alot of errors, like for example:

  • chart = new myChart (...) should be chart = new Chart (...)
  • new Chart (ctx {...}) a comma is missing between ctx and the config object, so new Chart (ctx, {...}).
  • in the config object options={ the equal sign should be a colon options:{
  • pushData(xhr.responseText); is passing a string to the pushData function, but in the function your are accessing two parameters function pushData(xData, yData) { ... }. xData and
    yData this will not work. xData will always be the returned data and yData will be always undefined.

those are the ones I caught just browsing your code.

btw.: you can check what the Ajax call returns, if you output the result to the console. AND xhr.responseText is a string, not a json object (use JSON.parse(xhr.responseText) to convert this, for example).

    var xhr = new XMLHttpRequest();
    var handlerUrl = '/Index?handler=Refresh';
    xhr.open('GET', handlerUrl, true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status == 200) {
                console.info(xhr.responseText);
                return;
            }
            console.log("error happens: receives a status code ", xhr.status)
        }
    }
    xhr.send();

Bonus Info:
If you don’t need to support older browsers, instead of the XMLHttpRequest I would recommend fetch (link to mdn documentation), this is the "modern way" and easier to use.

The following code is comparable to your XMLHttpRequest code piece, is much shorter and easier to read.

fetch('/Index?handler=Refresh')
    .then((response) => response.json())  
    // And data will be a json object and no convertion needed
    .then((data) => console.log(data));

Leave a comment