Interactive sparklines powered by Highcharts with dynamically loaded AJAX data

If you have an HTML table and want to display sparkline charts from your data, check out this example from Highcharts demos:

https://codepen.io/_dario/pen/rNBOGVR

Highcharts provides the suggested code below:

/**
 * Create a constructor for sparklines with default options that can be merged with chart options.
 */
Highcharts.SparkLine = function(a, b, c) {
  var hasRenderToArg = typeof a === 'string' || a.nodeName,
    options = arguments[hasRenderToArg ? 1 : 0],
    defaultOptions = {
      // Options here
    };

  options = Highcharts.merge(defaultOptions, options);

  return hasRenderToArg ?
    new Highcharts.Chart(a, options, c) :
    new Highcharts.Chart(options, b);
};

// Code snippet for generating sparkline charts

function doChunk() {
  // Code for processing sparkline data in chunks
}

doChunk();

In your use case, the data in the table (and the data-sparkline attribute) are loaded dynamically via AJAX, as shown in the following example:

// Example of dynamic data loading for sparkline charts

var tableRow = '<tr id="row_' + word.id + '">';
tableRow += '<td class="has-sparkline"></td></tr>'
$('#wordstable tbody').append(tableRow);

var rowId = '#row_'+word.id;
var rowIdTd = rowId + ' td.has-sparkline';
$(rowIdTd).data('sparkline', word.sparkline);

This approach may disrupt the logic of the initial example, preventing Highcharts from recognizing the data.

If no errors are returned, it indicates that the data is not being recognized by Highcharts due to the dynamic loading process.

Answer №1

The doChunk function is responsible for processing data in advance so that when a new row is added, the processing is already completed. To address this issue, one approach is to extract the part that generates a single chart into a separate function called makeChart. Then, during the processing phase, you can directly utilize this function to create your sparkline.

Illustratively, doChunk separates out makeChart:

function makeChart(td) {
    $td = td;
    stringdata = $td.data('sparkline');
    arr = stringdata.split('; ');
    data = $.map(arr[0].split(', '), parseFloat);
    chart = {};

    if (arr[1]) {
      chart.type = arr[1];
    }
    $td.highcharts('SparkLine', {
        series: [{
            data: data,
            pointStart: 1
        }],
        tooltip: {
            headerFormat: '<span style="font-size: 10px">' + $td.parent().find('th').html() + ', Q{point.x}:</span><br/>',
            pointFormat: '<b>{point.y}.000</b> USD'
        },
        chart: chart
    });

}

// Generating 153 sparkline charts is efficient on modern browsers, but IE8 and mobile devices may take longer
// Therefore, the input is split into chunks and processed with timeouts to prevent browser freezing and enable interaction.
function doChunk() {
    var time = +new Date(),
    i,
    len = $tds.length,
    $td,
    stringdata,
    arr,
    data,
    chart;

    for (i = 0; i < len; i += 1) {
        makeChart($($tds[i]));

        n += 1;

        // If the process exceeds a certain time limit, run a timeout to maintain browser responsiveness
        if (new Date() - time > 500) {
            $tds.splice(0, i + 1);
            setTimeout(doChunk, 0);
            break;
        }

        // Provide feedback on performance
        if (n === fullLen) {
            $('#result').html('Generated ' + fullLen + ' sparklines in ' + (new Date() - start) + ' ms');
        }
    }
}

Here is a basic example of ajax-code integration:

function ajaxIsh() {
    var word = {
        name: 'Bird',
        id: 'bird',
        sparkline: '1, 2, 3, 4, 5'
    };

    // Compile the table row here
    var tableRow = '<tr id="row_' + word.id + '">';
    
    // Insert sparkline data
    tableRow += '<th>' + word.name + '</th><td class="has-sparkline"></td></tr>';
    
    // Append the row to tbody
    $('#table-sparkline tbody').append(tableRow);

    // Attach sparkline data 
    var rowId = '#row_' + word.id;
    var rowIdTd = rowId + ' td.has-sparkline';
    $(rowIdTd).data('sparkline', word.sparkline);

    makeChart($(rowIdTd));
}

View a live demonstration of this implementation in action on JSFiddle.

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

I'm having difficulty saving a key-value pair in a log file

const FileHasher = require("./FileHasher"); if (process.argv.length < 3) { console.log("Please provide a program file and one argument."); process.exit(1); } const filename = process.argv[2]; const fs = require('fs'); const file = fs.rea ...

Rails 6 application experiencing issues with links not functioning properly until the page is refreshed

I recently followed a tutorial on GoRails to integrate EasyAutoComplete into my Rails application, which you can watch here: https://www.youtube.com/watch?v=ibxlNN73UTY While the search bar functions correctly as demonstrated in the tutorial, I encounter ...

Analyzing XML markers

Extracting specific values from XML tags We are looking to extract and display only the tags that contain the words "sports" and "secure" within the <str name="word">WORD</str> tag in the following XML: XML <response> <lst name ...

What are some key indicators in the source code that differentiate TypeScript from JavaScript?

Reviewing some code on Github, I am looking for ways to quickly determine whether the script is written in JavaScript or TypeScript. Are there any simple tips or hints that can help with this? For instance, when examining an array declaration like the on ...

Utilizing the power of AngularJS with ng-class for dynamic styling and

I recently started learning AngularJs and I have a question about how angular handles the ng-class attribute. While working with external libraries for visualization, charts, etc., I often need to trigger the resize event: window.dispatchEvent(new Event( ...

Arrays are not being successfully passed to the controller action during an Ajax call

I have encountered an issue where I am passing an array variable to the controller. Despite the data being present in the array from the ajax call, when the controller is called it shows count=0. var url = '@Url.Action("UserRoleCompany_AddUserAcce ...

Is it not possible to utilize inline "if" statements in conjunction with useEffect within a functional React component?

I'm currently working on integrating Okta's React SDK into a TypeScript-based application using functional components instead of class-based ones. My main challenge lies in rendering a part of the app's menu based on the user's authenti ...

Is there a way to use AJAX to include an external PHP file into a WordPress website

I'm having trouble calling a file in a WordPress plugin using ajax. Here is the script I'm using: <script type="text/javascript"> function setVal() { var val = jQuery('#custom_text_message').val() alert('Setting the ...

How do I show a variable within my react-native render function?

I attempted to showcase information fetched by a function in my React Native rendering application. Even though I successfully retrieved the data, I am encountering issues when trying to display it on the app. This is the snippet of my code: import Reac ...

Integrate javascript into a Wordpress loop while specifying which class to target

Seeking assistance on integrating category icons with animations using snap.svg in a Wordpress page. I have inserted a div containing an svg within the loop that generates the page (index.php). The divs display correctly with the appropriate size of the ...

Whenever a form is generated dynamically, it consistently encounters a 403 forbidden error when attempting to make a POST request

I am encountering an issue with editing text posts on my website. Whenever I click the edit button, a form is dynamically created to replace the div element. I have set up a POST api in Django to handle the submission of this form and edit the existing pos ...

Encountering Error with Axios in Nuxt while Navigating Pages

Working on a nuxt application utilizing axios for API calls. In my index.vue file, I have the code snippet below. <template> <div> <Hero /> <Homebooks :details="details" /> </div> </template> <s ...

Unexpected results with Euler angles in Three JS when applied to a basic box mesh

My dilemma involves a box located in the global axis system XYZ. I am trying to rotate this box to align with a new axes system X'Y'Z' The vectors for the new axes are: X' = (0,1,0) Y' = (1,0,0) Z' = (0,0,-1) This informatio ...

Submitting form data triggers an AJAX request that retrieves and displays the desired content within a

When it comes to opening search results in a specific form on a webpage using Ajax, many developers may face certain challenges. Here is an example of how it can be implemented: <form id="searchForm" method="GET" > <INPUT TYPE="text" N ...

Decoding a JSON object in node.js

{"__v":0,"_id":{"$oid":"55f13d34258687e0bb9e4385"},"admin":true,"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3d6ded2c3dfd682f3d4ded2dadf9dd0dcde">[email protected]</a>","last_login":"11:25:24 AM","name ...

JavaScript does not recognize external styles (when an if statement is involved)

I recently started learning web development, and I encountered an issue while working on a responsive design project. When the hamburger menu is clicked, the lines for expansion that are defined in an external CSS file are not being detected. Instead, new ...

`Is it possible to interpret HTML using AutoHotkey?`

I am struggling with the parsing of HTML files. The examples I have come across are quite complex for a beginner like me, making it difficult to understand. Although I've tried reading the GetNestedTag manual, I believe there might be a simpler soluti ...

I am experiencing significant lag when attempting to use the Vue mouseover event to manipulate the styles of two elements. Are there any alternative methods that could achieve the same

I'm fairly new when it comes to using Vue, so I might not be approaching this in the most efficient manner. My challenge involves a table of rows generated via a v-for loop, accompanied by a list of corresponding row titles also created through a v-fo ...

Assign the JSON data to a variable

Can someone help me figure out how to save a JSON file from a URL in a variable and then work with it? Normally, it looks something like this: var jsonOriginal = { name: "Steve", age: 27, jobTitle: "Program Manager" }; alert(person.name); But now I need ...

Issue: Retrieve comments via AJAX (from database) in Laravel 5.2

Currently, I am developing a comments section for posts where users can leave comments without the need to refresh the page. However, I am facing an issue in displaying these comments instantly on the post without any page refresh. This is how I have stru ...