The graph does not render correctly when updating chart.js using AJAX

My attempt to create a line chart using chart.js with AJAX seems to be failing when the data comes from the server. The chart displays correctly when the window loads, but fails to render properly with AJAX. What could be causing this issue? Here is my code:

index.html:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>AJAX JSON Chart</title>
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<script type="text/javascript">
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var lineChartData = {
    labels : ["January","February","March","April","May","June","July"],
    datasets : [
        {
            label: "My First dataset",
            fillColor : "rgba(220,220,220,0.2)",
            strokeColor : "rgba(220,220,220,1)",
            pointColor : "rgba(220,220,220,1)",
            pointStrokeColor : "#fff",
            pointHighlightFill : "#fff",
            pointHighlightStroke : "rgba(220,220,220,1)",
            data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
        }
    ]

}

window.onload = function(){
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
    responsive: false
});
}

// ajax part of chart //
$(document).ready(function(e) {
    $("#frm1").submit(function(){
    var canvas = document.getElementById('canvas');
    ctx = canvas.getContext('2d');

    var btnchart = $("#btnchart").attr("name") + "=" + $("#btnchart").val();
        $.ajax({
            //beforeSend: function(){ sendRequest("canvas"); },
            cache: false,
            type: "POST",
            dataType: "json",
            url: "ajax/chart.php",
            data: $(this).serialize() + "&" + btnchart,
            success: function(data){
                //alert(data.labels);
                //alert(data.points);
                renderGraph(data.labels, data.points, ctx);
            },
        });
    return false;
    });
});

var renderGraph = function (labels, points, ctx) {

        var lineChartData = {
                        labels: "[" +  labels + "]",
                        datasets: [
                            {
                                label: "Recent Orders",
                                fillColor: "rgba(220,220,220,0.2)",
                                strokeColor: "rgba(220,220,220,1)",
                                pointColor: "rgba(220,220,220,1)",
                                pointStrokeColor: "#fff",
...

</script>
</head>
<body>
<div style="width:30%">
    <div>
        <canvas id="canvas" height="450" width="960"></canvas>
    </div>
</div>
<form id="frm1" name="frm1" method="post" action="">
<input type="submit" name="btnchart" id="btnchart" value="Draw Chart" />
</form>
</body>
</html>

chart.php:

<?php
$labels = array('29 April 2015', '30 April 2015', '1 May 2015', '2 May 2015', '3 May 2015', '4 May 2015', '5 May 2015');
$points = array('100', '250', '10', '35', '73', '0', '25');
echo json_encode(array('labels' => $labels, 'points' => $points));
?>

The initial output when the page loads for the first time is:

After clicking the "Draw Chart" button, the output received through AJAX is:

However, oddly enough, hovering over the image causes it to revert back to the correct graph that was initially displayed on window load. Strange!

Answer №1

Before re-creating your chart, you should first remove the previous chart by executing:

myChart.destroy();

Alternatively, you can use:

myChart.clear();

After that, you can proceed to draw your chart again. This should ensure it functions properly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to retrieve real-time information from an API by utilizing the HTTP.Get method?

When working with ANGULAR I am faced with the challenge of pulling data from an API using http.get at regular intervals. The API continuously updates minute by minute traffic data, and I need Angular to display these live updates. Currently, my approach ...

Having trouble creating an axios instance in Vue

I recently came across a helpful tip in an article about using axios for AJAX requests in Vue. The author mentioned that by setting Vue.prototype.$http = axios, we can then use this.$http within the Vue instance, which worked perfectly for me. However, wh ...

Python in the backend working with Ajax

Currently, I am developing a web application on Google App Engine with Python as the back-end. I now want to incorporate Ajax-like features into my site. However, most of the tutorials I came across focus on using PHP for the back-end. My question is, can ...

What are the best scenarios for utilizing ajax methods in testing? How can I determine the optimal situations for their use?

As a beginner in automation, I have been introduced to ajax methods for clicking elements. However, I am unsure of when and where to use them effectively. Currently, my approach is to resort to ajax if traditional clicking methods fail. But how can I deter ...

Issue with element failing to register click event

While dynamically generating HTML through javascript, I encountered an issue with the delete glyph not responding correctly within a table cell. The pencil glyph works fine, but for some reason, the delete function is not working as expected. Here is the ...

How to import an HTML file using TypeScript

I need to load an html file located in the same directory as the typescript file and return it from the function. public ...(... ) : angular.IHttpPromise<string> { ... return $http({ method: 'GET', url: &apos ...

JQuery Mobile Listview Filter Not Working: Troubleshooting Tips

Recently diving into the world of jquery mobile, I've managed to successfully create a homepage and a sub-page labeled "bible_studies," complete with a dynamic list generated through AJAX. Everything seems to be functioning perfectly except for one i ...

SwitchClass or AppendClass are not compatible with input tags

I am having trouble changing the border color of an input element using jQuery. Here is the setup: <input id="box" type="text" /> And the CSS class I am trying to toggle: .box-change { border-color:#ffffff; } Below is the jQuery code I am usi ...

What methods can be used in the debugger to intentionally cause a javascript-based AJAX request to fail for testing purposes?

Imagine if I implemented code to manage scenarios where the AJAX request fails, how can I effectively test it? Is there a method to intentionally cause an AJAX request to fail using the Chrome debugger? ...

Utilizing Angular 2's offline capabilities for loading locally stored JSON files in a project folder

I've been attempting to load a local JSON file from my Angular 2 project folder using the HTTP GET method. Here is an example of the code snippet: private _productURL = 'api/products/products.json'; getProducts(): Observable<any> ...

Numerous criteria for selecting a checkbox

I am working with a student database table called student_db, which looks like this: Name Gender Grade City John Male 2 North Dave Male 4 North Garry Male 3 North Chirsty Female 5 East Monica Female 4 East Andrew Male ...

JavaScript and inverted brackets

Why does Javascript allow the use of inverted parentheses in function calls? I'm currently using a Node console on the CLI with Node version 0.10.25. function a(){ return 42 } a() // -> 42 a)( // -> 42. Strange behavior? function b(t){ return ...

What is the best way to assign a series of radio buttons to an array within an Angular controller's model?

Let's say I have a controller that contains an array property named 'houses'. I want to use ng-repeat to display this array on a table row with a set of radio buttons (true/false, etc.). How can I ensure that selecting any of these radio but ...

A step-by-step guide on effectively mocking the 'find()' function in Mongoose using Jest

My service has the following code snippet: export default class WorldService { constructor(worldModel) { this.worldModel = worldModel; } async getWorlds() { let resData = {}; await this.worldModel.find({}, (err, worlds) => { res ...

Is it possible to include a callback function or statement following a $timeout in AngularJS?

function fadeAlertMessage() { $scope.alertMessagePopUp = true; $timeout(function() { $scope.fade = true; }, 5000) function() { $scope.alertMessagePopUp = false; } I'm facing a challenge and I'm seeking assistance with this is ...

Sequelize JS - Opting for the On clause in join operations

Seeking guidance on selecting the appropriate ON clause for a join. I am working with two tables - packages and users. The package table contains two fields/columns (owner_id, helper_id) that serve as foreign keys to the same users table. My goal is to per ...

Retrieve information from an API service seamlessly without the need to refresh the web browser

I am currently using a combination of Spring Boot with Angular. I have a method in place that fetches data from an API service every second, but I keep encountering the following error message: core.js:6185 ERROR TypeError: You provided 'undefined& ...

Do not use Express.js to serve the index.html file

Encountered an issue when attempting to run my Express.js solution. Instead of opening my desired index.html file located in the client directory, it kept opening the index.jade file from the views folder with the message "Welcome to Express" on the browse ...

Steps for creating a sleek vertical slider with transitional effects using JavaScript and HTML

Take a look at my code snippet: <table> <tr> <td onclick="shownav()">Equations of Circle <div id="myDownnav" class="sidenav"> <a>General Info</a> <a>In Pola ...