Visualizing dynamic data with Ajax in a column bar chart

Trying to implement highcharts column bar charts, but facing issues with refreshing the data without reloading it. Unfortunately, I don't have access to the code I used at work to resolve this.

Considering setting up a loop to run multiple times with a 5-second delay. Unsure about the best approach.

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Highcharts Example</title>

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script type="text/javascript">
< your typical ajax call function here
    return some value;
>


$(function () {
    <var ajax_far = ajax_function();>
    var chart;
    $(document).ready(function() {
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'container',
                type: 'column'
            },
            title: {
                text: 'Monthly Average Rainfall'
            },
            subtitle: {
                text: 'Source: WorldClimate.com'
            },
            xAxis: {
                categories: [
                    'Some Bar'
                ]
            },
            yAxis: {
                min: 0,
                title: {
                    text: 'Rainfall (mm)'
                }
            },
            legend: {
                layout: 'vertical',
                backgroundColor: '#FFFFFF',
                align: 'left',
                verticalAlign: 'top',
                x: 100,
                y: 70,
                floating: true,
                shadow: true
            },
            tooltip: {
                formatter: function() {
                    return ''+
                        this.x +': '+ this.y +' mm';
                }
            },
            plotOptions: {
                column: {
                    pointPadding: 0.2,
                    borderWidth: 0
                }
            },
                series: [{
                name: 'Tokyo',
                data: [ajax_var]

            }]
        });
    });

}, 5000);
        </script>
    </head>
    <body>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>

<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>

    </body>
</html>

Answer №1

Instead of scattering your ajax code throughout your script, consider encapsulating it in a single function that you can call from the document ready function. Here's an example to demonstrate how you can structure your code:

$(document).ready(function(){
    executeAjax();
    setInterval(executeAjax, 5000);
});

function executeAjax(){
    // Place your ajax code here
}

Answer №2

When using ajax to update a chart, you only need to fetch new data without redrawing the entire chart. You can simply replace the series data or add individual points. For guidance on implementing this with Highcharts, check out this helpful article here. Here is an example of ajax code recommended by them:

/**
 * Request data from the server, add it to the graph and set a timeout to request again.
 */
function requestData() {
    $.ajax({
        url: 'live-server-data.php',
        success: function(point) {
            var series = chart.series[0],
                shift = series.data.length > 20; // Shift if the series is longer than 2.

            // Add the point.
            chart.series[0].addPoint(point, true, shift);

            // Call it again after one second.
            setTimeout(requestData, 1000);    
        },
        cache: false
    });
}

In this code snippet, the requestData function is called every second (using setTimeout). It fetches a new data point through an ajax call to live-server-data.php and adds it to the chart using chart.series[0].addPoint.

If the ajax call returns the entire series, you can use chart.series[0].setData to replace the whole series.

The important thing to remember is to ensure that the chart is created before calling addPoint or setData.

Answer №3

   $(function () {
    var myChart;
    var myList;
    $(document).ready(function() {
        var config = {
            chart: {
               //customize your chart attributes here
                 }
                //add any other attributes
           }
 myChart = new Highcharts.Chart(config);
    setInterval(function() {
        $.ajax({
        type: "GET",
        url: "service",
        dataType: "json",
        success: function (data) 
    { 
           myChart.series[0].setData(data);
        }
    }),1000); //will update the chart with ajax data every second, use addPoint() if you want to append data
});
});

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

Preventing cross-site scripting attacks with the help of dynamic pre elements

An expert recommended that the user content, replyContent, be surrounded by a <pre> tag to prevent XSS attacks. However, why is it commonly believed that this code effectively prevents XSS? I attempted to inject </pre><script>alert("XSS" ...

Issues with Jquery Ajax implementation causing data not to display in HTML

Hey team! I've got an ajax function set up (see code below) that sends data to a php file, retrieves it, and posts it in an html div. I have two different pages within the same folder using this code - one is 'loggedout' and the other is &a ...

Currently, only the initial button is functional. I am uncertain if it is due to a script issue or if there is a rule that I inadvertently

As a beginner, I am eager to grasp the fundamentals and rules of Javascript. My goal is to create a basic example that involves a box with three buttons. However, I have encountered an issue where only one button seems to be functional despite having dis ...

Pause file uploads, display modal popup, then resume uploading

Is there a way to pause file uploading in order to display file requirements before proceeding? For example, when a user clicks on "upload file", I would like to show them a modal window with details about the file they need to upload. Once they click ok, ...

Having trouble understanding how to incorporate jQuery GetListItems with SharePoint SOAP - it seems simple, but can't figure it out!

I'm attempting to incorporate a SharePoint list into an Unordered List to set up a basic search function (since Sharepoint's Search functionality is quite lacking). Below is the code I found and adjusted: $(document).ready(function() { v ...

What is the method for utilizing string interpolation in Angular/Typescript in order to retrieve a value from a variable?

I have a variable called demoVars, which is an array of objects with properties var1, var2, and var3. In my component class, I have a variable named selectedVar that holds the name of one of these properties: var1, var2, or var3. I want to dynamically pu ...

The loading indicator is not appearing inside the designated box

I have successfully implemented a loader using jQuery and CSS to display a gray background during an AJAX call. However, I am encountering an issue where the loader and background are being displayed across the entire page instead of just within a specific ...

Is it possible to use the Stop Button on the HTML5 Audio Tag to halt a live MP3 stream

Is there a way to add a stop button as well? Currently, I have play and pause buttons, but the stop function doesn't truly clear the music buffer in the browser; it just stops playback without resetting to the beginning. This is fine for MP3 files but ...

Using ngModel to retrieve and display only the month, year, and date

Currently, I am working with an interface named Person which includes fields such as name, last name, birthday, and others. However, I am facing a confusion when it comes to the person's birthday format, as it contains some additional letters at the e ...

Using Javascript to upload an image and show it in a small display

Hey there, I have a functioning JavaScript code that loads an image uploaded by the user onto the HTML page. However, the issue is that the image doesn't have a set maximum height or width, causing buttons on the page to move out of view and become in ...

Guide to utilizing exact matching functionality in ExpressJs router

In my ExpressJs application, I have defined two routes like so: router.get("/task/", Controller.retrieveAll); router.get("/task/seed/", Controller.seed); When I make a request to /task/seed/, the Controller.retrieveAll function is call ...

WebSocket functionality in Node.js utilizing the ws module from npm

I am currently working on developing a chat application. The first step involves the user sending their username, and if the name does not already exist, they are logged in. The user can then send a message to another user. However, an issue arises where a ...

By implementing Async.parallel, I ensure that the lifetime of my parameter does not exceed the duration of the asynchronous calls in NodeJS when working with MongoDB

After analyzing the code and its asynchronous behavior, it appears that the 'recipeData' array may not persist long enough to handle the asynchronous callbacks. To mitigate this, I created a copy of the data in a global array. However, I am encou ...

Creating a Custom Class for a Custom Button in TinyMCE 4 Using addButton()

Is there a way to add a custom class to a custom button using the addButton() function in TinyMCE? Here is an example: editor.addButton('keywords', { text: 'Insert Keywords', class: 'MyCoolBtn', ...

Trouble with Displaying Angular Template using ng-hide

I am encountering an issue with my angular directive that is used to display a button form. The template remains hidden until it needs to be displayed for the user. Although the template works fine on its own, it does not appear when integrated into the la ...

Tips for Preventing Unnecessary Ajax Requests

What I require When a click event is triggered, a service call should be made only once. Use case Dropdown1 Dropdown2 Dropdown3 1. There are three dropdowns on the HTML page. 2. When Dropdown1 is called - an AJAX call is made only onc ...

What is the process for sending JavaScript with an Ajax request?

Working with ajax and javascript for the first time, I'm no expert in web development. Here is the code I've written and tested so far. I have a select div containing some options. <select id="month" onchange="refreshGraph()"> When an op ...

Utilizing the Replace function just once

I am currently using the Avada Theme on Wordpress and I am attempting to use jQuery to translate the social media privacy labels/content. Everything is working smoothly except for one issue. Below is the HTML code: function translate() { jQuery(".fus ...

Effective techniques for managing PHP forms within HTML and CSS by utilizing checkboxes:

I'm struggling with my code, particularly the form section. Here is the HTML code snippet: <form action="index.php/homepage/deleteSelected" method="POST"> <input type="submit" value="Delete Selected"> ...

What is the method to retrieve text from a div element with Webdriver-IO?

Is there a way to extract the value from the following HTML element using Webdriver-IO for automated testing? <div class="metric-value ng-binding" ng-style="{'font-size': vis.params.fontSize+'pt'}" style="font-size: 60 ...