0

I am new to Django , i Have used chart.js to populate a chart in HTML . I want to refresh the chart without loading the HTML itself.

HTML Chart look like below

CHart present in HTML

View corresponding to the URL for above HTML is below

**Views.py**

   from __future__ import unicode_literals

from django.shortcuts import render
from django.views.generic import TemplateView
# Create your views here.
def dashboard(request):
    if request.is_ajax():
        print "this is ajax request inside dashboard function"
        pass_tc=29
        failed_tc=25
        inprogress_tc=25
        data = {'data':[pass_tc, failed_tc, inprogress_tc]}
        request.GET.get('data')
        print JsonResponse(data)
        return JsonResponse(data)

    context = {'data':[500,100,50]}
    template='dashboard.html'

    return render(request,template,context)



]

In HTML , i have used updateChart() functionality of Chart.js

<button class='btn btn-success' onclick="updateChart()">Refresh</button>

         <script>
        var ctx = document.getElementById('myChart').getContext('2d');
        var chart = new Chart(ctx, {
        // The type of chart we want to create
        type: 'bar',

        // The data for our dataset
        data: {
        labels: ['Pass', 'Fail', 'Inprogress'],
        datasets: [{
            label: 'Results',
            //backgroundColor: 'rgb(255, 99, 132)',
            //borderColor: 'rgb(255, 99, 132)',
            backgroundColor:[
            'green','Brown','orange'],
            data: [10, 10,15]
        }]
        },

    // Configuration options go here
        options: {},

        });
        function updateChart(){

   $.get("/dashboard/",{data:response.JsonResponse(data)}, function(data, status)
    {
        //console.log(data)

        chart.data.datasets[0].data={{data}};
        chart.update();
    }


        )


        };

On the server side i can see below response

this is ajax request inside dashboard function
Content-Type: application/json

{"data": [29, 25, 25]}
[15/Apr/2019 18:52:12] "GET /dashboard/ HTTP/1.1" 200 22

So the Ajax request is fetching the data . However my chart is not getting populated with this data.

it uses the non Ajax data defined in View.py, also shown in graph i.e.

{'data':[500,100,50]}

What wrong i am doing in my Ajax request.

pankaj mishra
  • 2,099
  • 2
  • 13
  • 29

1 Answers1

2

When django return rendered template to client, it won't be able to make any changes afterwards. That's why your chart doesn't reflect any changes made in django.

If you need to update your chart with new data, easiest solution will be to use AJAX request.

  • User press Refresh button
  • Javascript send GET request to django API point
  • Django serve new values in JSON back to user
  • Javascript will update chart with new values

Make another endpoint, something like this:

from django.http import JsonResponse

def dashboard_ajax_chart_data(request):
    pass_tc=500
    failed_tc=99
    inprogress_tc=50
    data = {'data':[pass_tc, failed_tc, inprogress_tc]}
    return JsonResponse(data)

Make function in your javascript code, like this:

jQuery('.refresh-button').click(function(){
        jQuery.getJSON("/dashboard_ajax/", function(data, status)
        {
            chart.data.datasets[0].data = data.data;
            chart.update();
        }
        )
});

and make this function execute when you click on your refresh button.

I don't have proper experience with chart.js, but use this guide to update your chart. https://www.chartjs.org/docs/latest/developers/updates.html

Gasanov
  • 2,264
  • 1
  • 7
  • 16
  • I have edited my code as per your suggestion, but still the same issue!! All the relevant information i have updated in my original question. – pankaj mishra Apr 15 '19 at 09:58
  • @pankajmishra Did you add new endpoint to `urls.py`? Does django serve request? Do you receive new data in your javascript? Debug it with `console.log(data)`. – Gasanov Apr 15 '19 at 11:36
  • That's because your `urls.py` uses the same function for both endpoints. – Gasanov Apr 15 '19 at 13:41
  • I have edited my code and question, looks like there is some problem in fetching the response from Ajax query. – pankaj mishra Apr 15 '19 at 13:41
  • Try version with [$.getJSON](https://api.jquery.com/jQuery.getJSON/) - chances are your response is not interpreted as JSON – Gasanov Apr 15 '19 at 14:07
  • And fix curly brackets in javascript code - my answer has updated code – Gasanov Apr 15 '19 at 15:21
  • Same result!! Somehow the data returned by Ajax is not being picked in Ajax response. – pankaj mishra Apr 16 '19 at 07:12
  • i have simplified my question, may be you can have a look https://stackoverflow.com/questions/55703619/chart-is-not-getting-updated-from-the-values-it-received-from-jquery – pankaj mishra Apr 16 '19 at 08:31
  • @pankajmishra you should change it to `chart.data.datasets[0].data = data.data` – Gasanov Apr 16 '19 at 08:38