MODX Community

Chart.js Dynamic Update - AJAX

Hi everyone,

I am currently using a DateRangePicker in combination with some radio-buttons to display a chart. The problem is that I am using PHP and therefore the page has to be reloaded every time I change the dates.

I tried with AJAX but had some struggle to recalculate the entire canvas again and to overwrite the container with the ‘old’ canvas.

My idea with AJAX was to create a 2nd document which calls a snippet that is only used to calculate the entire canvas in PHP with the results of the SQL query. But how do I get that result to the initial document?

Here’s a gif of how it currently looks.

Thanks in advance.

1 Like

One way is to create a processor file (with a class that extends modProcessor or one of it’s descendants). Make your Ajax call to that processor and have the processor return the canvas.

1 Like

I think I need some more clarification. It sounds like you want to know how to update the dataset Chart.js is using without reloading the page. However, your GIF appears to be demonstrating this behavior already, which leads me to think I don’t understand what you’re asking. Would you mind explaining further?

The GIF is cut, that’s why it appears to be the desired behavior. The chart is at the very end of a page which means that every time I press the calendar button, I have to scroll down.

What I’d like to achieve is to change the datasets dynamically without reloading the page - in this case through a submitted form.
The struggle I have is that the datasets have to be requested by a query, which means that I would have to get the values from the daterange with e.g. jQuery, then I’d have to POST the dates with AJAX.

From that point on it would be redundant since I would call the first snippet again to execute the query with the new date range and then display the chart. But even if I did that anyways, how would I get that result (updated canvas) back to AJAX/jQuery to overwrite the first canvas?

You can include your $_POST data in a JavaScript AJAX call to a processor. The processor can return the new data and you can create the display with JS, or (probably easier) the processor can create and return the entire new chart. Either way the success method of the AJAX call call can modify the page using either one without a reload.

Thanks, it helped me a lot :slight_smile:

I’m glad I could help. :slight_smile: