Using ajax with Highcharts in Django

I recently started working with Django. I am currently developing a polls application and would like to incorporate highcharts for displaying graphs. In my template, I have all the poll questions listed and I want to display the corresponding poll results next to each question in the form of a chart. Here is a snippet from my 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 issue I'm facing is that the graph is only being displayed for the last poll question. Any help would be appreciated. Thank you.

Answer №1

The reason behind this issue is that the variable question_id gets overwritten in each of the for loops. A suggested alternative approach would be:

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

This way, you can iterate through each div after page rendering and display the appropriate chart.

For a more efficient solution, consider using data-id="{{ book.id }}" and fetching it using $(this).data('id') to avoid misusing the id attribute for unintended purposes.

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

PHP is failing to redirect the user to the correct index.php file

I encountered an issue in Jquery Mobile that has left me puzzled. Upon entering the site, users are prompted to either register or login. When selecting register, they are redirected to a page where they input their information. Once completed, the data is ...

Is it recommended to use gunicorn to serve Django on Google Cloud Platform's Standard Environment?

While the app engine quickstart guide for Django fails to address gunicorn in their sample Github Repo, the best practice remains unclear. Furthermore- Referencing the documentation on the Python3 runtime raises questions about whether including gunicorn ...

Issues with MySQL not functioning properly when using Promise.All in a Node.js environment

When it comes to running multiple mysql queries asynchronously in express node.js, MySQL works well with simple callbacks. However, I wanted to take it a step further by using async await with promise.all. I also experimented with promise.allSettled, but u ...

Add items to a new array with a property set to true, if they are present in the original array

Could someone assist me with the following situation? I need an array of strings. A function is required to map the array of strings, assigning each element a name and key, while also adding another object "checked: false". Another function should take t ...

"Concealing a div based on the toggling of another one - here's

Currently, I have a scenario where clicking on an image inside a div triggers the display of another div while simultaneously wanting to hide the original div containing the image. So far, utilizing only the abreInfo() function achieves the desired toggle ...

Have the input text and submit button aligned on the same line for a sleek

While attempting to create a search box and search submission button, I have tried various methods to align the button and text box on the same line without success. Below is the code snippet I am currently using. return ( <Form onSubmit={submitHa ...

Hide a div element upon selecting an option from a dropdown menu

On iPhone 6plus and lower, I created a dropdown menu that opens when users click on "jobs" or "contact." However, after clicking on these options, the drop-down menu remains open. How can I make it hide automatically after a list item is clicked at this sp ...

Sending an Ajax request using jQuery to a Jenkins job

var milestone_name = uiscripts.context.milestone.name; //AJAX block start $.ajax({ url: "https://ctu-automation-server:8080/job/Check/build", type: "GET" }); //AJAX block end When the above ajax call is made from a remote serv ...

Querying with conditions in Django's ORM

I'm in the process of creating a Blog website that allows users to like or dislike each post. My goal is to dynamically change the like button on the Index page based on whether the user has already liked the post or not. To achieve this, I need to re ...

Having trouble fetching AJAX POST data in PHP?

Attempting to send a variable as an object to my PHP file, but it's not receiving any data. Testing with window.alert(u.un) in the AJAX call shows that data is being passed successfully without errors in the console. However, the PHP file still does n ...

The integration of AngularJS with a redirect feature is causing issues with sending JSON data to the database

I have encountered an issue when trying to send JSON data to a backend database. Everything works perfectly until I introduce a redirect within the newPost function using "$window.location.href = 'success.html';" Once the redirect is added, no da ...

Leveraging v-for within a component that incorporates the <slot/> element to generate a versatile and interactive Tab menu

Currently, I am in the process of developing a dynamic tab menu using Vue 3 and slots. Successfully implementing tabs, I have created BaseTabsWrapper and BaseTab components. The challenge lies in using v-for with the BaseTab component inside a BaseTabsWrap ...

Error 534 occurred during SMTP authentication in a Django Python registration process

Although this question has been asked numerous times before, I am facing a slightly different situation. When deploying my Django app with django-registration-redux on Heroku, the registration works perfectly on my local machine but gives an SMTPAuthentica ...

Component template using Knockout.js and RequireJS for HTML widgets

Trying to implement the widget example for knockout from here. Unfortunately, I am having issues loading the template from an external HTML file using requirejs. ko.components.register('like-or-dislike', { template: { require: &apos ...

Error loading configuration for Solr core in Django application

After executing $ python manage.py build_solr_schema, I pasted the resulting content into the file located at examples/solr/blog/conf/schema.xml. My Django project is integrated with Apache Solr 4.10.4, but upon running Apache Solr, an error occurred: Sol ...

In React Native, what exactly does it signify when you run the packager with the `--clearCache` flag?

Whenever I run my React Native apps, I rely on the command react-native run-ios. However, while debugging, it recommended using the "--clearCache" flag when running the packager. Can someone explain what this suggestion means? What exactly is the package ...

Issue with Jquery Drag and Drop functionality, navigate to a different page

I am trying to incorporate a page with js from quotemedia.com using Jquery. When I insert the js into the sortable, and then drag and drop the element containing the js, it suddenly switches to full page display. This issue occurs in Firefox, but IE works ...

Error: Unable to load the JSON file from the specified URL due to an XMLHttpRequest restriction

I've been struggling to read a JSON file from a URL and display it. Despite searching through multiple forums, I can't seem to fix the issue. Here's the URL: The error message I'm encountering is: XMLHttpRequest cannot load. Below is ...

Is there a way to superimpose text onto an image within a ReactJS/NextJS application?

I'm facing issues with applying CSS styles properly in my ReactJS/NextJS application. I am working on a component that displays an image with text overlaid on it. Despite testing the styles on w3schools, I cannot seem to get them to work correctly in ...

Embed the AJAX response into HTML format

I am facing a challenge with rendering an AJAX response in an HTML structure within a PHP file. The issue is that the AJAX response contains multiple data objects, and each of them needs to be placed in specific locations within the HTML. For example, let ...