bharat agarwal bharat agarwal - 3 months ago 21
Javascript Question

Highcharts in Django using ajax

I am new to Django. I am making polls application and want to use highcharts to display graphs. I have a template which displays all the polls. I want to show the corresponding results of poll beside it in form of chart. Part of the template:

{% for question in poll_questions %}
<div class="col-sm-6">
<div class="panel panel-default">
<div class="panel-body">
<div class="row">
<div class="col-sm-12">
{{question.question_text}}
{% for choice in question.poll_choices_set.all %}
<div>
<label><input type="radio" name="{{question.pk}}" value="{{ choice.pk }}">&nbsp {{choice.choice_text}}</label>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-6">
<div id="{{ question.pk }}" class="chart" style="height: 400px; width: 400px"></div><br>
<script>
var question_id = '{{ question.pk }}'
</script>
<script src="{% static 'er_interface/polls.js' %}"></script>
</div>
{% endfor %}


Javascript file- polls.js:

$.getJSON('/er/poll/'+question_id ,function(data) {
$('#'+question_id).highcharts({

chart: {
type: 'pie'
},
title: {
text: question_id
},
tooltip: {
pointFormat: ':<b>{point.y}</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
},
series: {
dataLabels: {
enabled: true,
formatter: function() {
return Math.round(this.percentage*100)/100 + ' %';
},
distance: 0,
}
}
},
series: data
});
});


The problem is that graph is shown just for the last poll question. Thanks

Answer

This is because in each of the for loops, question_id is overwritten. You might want to do something like this instead:

$('.chart').each(function() {
    var that = this;
    var question_id = $(this).attr('id');
    $.getJSON('/er/poll/'+question_id ,function(data) {
        $(that).highcharts({
            ...

That way, after rendering the page, you loop through each of the divs and render the appropriate chart.

Even better: use data-id="{{ book.id }}" and retrieve it with $(this).data('id') do avoid using the id attribute for something it's not really meant for.

Comments