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 bechart = new Chart (...)
new Chart (ctx {...})
a comma is missing betweenctx
and the config object, sonew Chart (ctx, {...})
.- in the config object
options={
the equal sign should be a colonoptions:{
pushData(xhr.responseText);
is passing a string to thepushData
function, but in the function your are accessing two parametersfunction pushData(xData, yData) { ... }
.xData
and
yData
this will not work.xData
will always be the returned data andyData
will be alwaysundefined
.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));
- Chartjs-How do I make the legends tab focusable in a chart.js Line chart using React.js?
- Chartjs-How can I have smaller labels with Chart.js?