Dynamic data not being recognized by anychart library

I have integrated anychart to create a chart on my webpage. Here is the code I am using:

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>    
<script src="https://cdn.anychart.com/js/7.12.0/anychart-bundle.min.js"></script>
    <link rel="stylesheet" href="https://cdn.anychart.com/css/7.12.0/anychart-ui.min.css" />  
<input id="chart-charitytomoney" value="[[&quot;Charity 4&quot;,10.00],[&quot;Charity 2&quot;,20.00],[&quot;Charity Donate&quot;,100.00],[&quot;Donate Your Humanity&quot;,5920.00],[&quot;Gift your Work&quot;,3155.00],[&quot;Celebrate Baby Shower&quot;,770.00],[&quot;Refer Friends&quot;,110.00],[&quot;Gift Your Friends&quot;,200.00],[&quot;Celebrate B\u0027day With Us&quot;,220.00],[&quot;Celebrate Weekend&quot;,50.00],[&quot;Piggy Bank&quot;,4100.00],[&quot;Give a Single Gift&quot;,4050.00]]">
<div id="chart-container" style="height:550px!important"></div>
            <script type="text/javascript">

                $(document).ready(function(){
                anychart.onDocumentReady(function () {
                    var data = $("#chart-charitytomoney").val();
                 
                    // create column chart
                    chart = anychart.column();

                    // turn on chart animation
                    chart.animation(true);

                    // set chart title text settings
                    chart.title('Charities by donation');

                    // create area series with passed data

                    alert(data);
var series = chart.column(data);

                    // set series tooltip settings
                    series.tooltip().titleFormatter(function () {
                        return this.x
                    });

                    series.tooltip().textFormatter(function () {
                        return '$' + parseInt(this.value).toLocaleString()
                    });
                    series.tooltip().position('top').anchor('bottom').offsetX(0).offsetY(5);

                    // set scale minimum
                    chart.yScale().minimum(0);

                    // set yAxis labels formatter
                    chart.yAxis().labels().textFormatter("${%Value}");

                    // tooltips position and interactivity settings
                    chart.tooltip().positionMode('point');
                    chart.interactivity().hoverMode('byX');

                    // axes titles
                    chart.xAxis().title('Product');
                    chart.yAxis().title('Revenue');

                    // set container id for the chart
                    chart.container('chart-container');

                    // initiate chart drawing
                    chart.draw();

                });
                });
            </script>

Upon initial inspection, everything seems to be in order. However, the chart does not seem to be working as expected. Interestingly, changing the following line of code makes it work:

var data = [["Charity 4", 10.00], ["Charity 2", 20.00], ["Charity Donate", 100.00], ["Donate Your Humanity", 5920.00], ["Gift your Work", 3155.00], ["Celebrate Baby Shower", 770.00], ["Refer Friends", 110.00], ["Gift Your Friends", 200.00], ["Celebrate B\u0027day With Us", 220.00], ["Celebrate Weekend", 50.00], ["Piggy Bank", 4100.00], ["Give a Single Gift", 4050.00]]

Could someone please help me identify what could be wrong with my original code? How can I fix it?

Answer №1

There is an interesting method for passing data which involves the following steps:

Option 1

To start, ensure you use quotes within the input field:

<input id="chart-charitytomoney" value="[['Charity 4',10.00],['Charity 2',20.00],['Charity Donate',100.00],['Donate Your Humanity',5920.00],['Gift your Work',3155.00],['Celebrate Baby Shower',770.00],['Refer Friends',110.00],['Gift Your Friends',200.00],['Celebrate B\u0027day With Us',220.00],['Celebrate Weekend',50.00],['Piggy Bank',4100.00],['Give a Single Gift',4050.00]]">

Then, make sure to evaluate the result using eval():

var data = eval($("#chart-charitytomoney").val());

For reference, here is a sample: http://jsfiddle.net/yr35w6nu/8/

However, it's important to note that eval is not entirely secure. If you prefer to store data as a string in a field like this, consider utilizing code similar to the one below:

Option 2

var data = JSON.parse($("#chart-charitytomoney").val().replace(/\'/g,'\"'));

As shown in this example: http://jsfiddle.net/yr35w6nu/9/

The same approach can be applied to your code with &quote; as demonstrated here:

var data = JSON.parse($("#chart-charitytomoney").val().replace(/\&quot;/g,'\"'));

An example of parsing quotes can be found here: http://jsfiddle.net/yr35w6nu/10/

Option 3

Another alternative is to store data in CSV format within the input field:

<input id="chart-charitytomoney" value="Charity 4,10.00;Charity 2,20.00;Charity Donate,100.00;Donate Your Humanity,5920.00;Gift your Work,3155.00;Celebrate Baby Shower,770.00\nRefer Friends,110.00;Gift Your Friends,200.00;Celebrate B\u0027day With Us,220.00;Celebrate Weekend,50.00\nPiggy Bank,4100.00\nGive a Single Gift,4050.00">

You can then utilize it in this manner:

var data = anychart.data.set($("#chart-charitytomoney").val(),{rowsSeparator: ';'});

For more information, visit: http://jsfiddle.net/yr35w6nu/13/

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

Exploring the Possibilities of OpenLayers with Scalable Vector

Trying to create a webpage with an image that can be navigated using drag and scroll events, similar to Google Maps. Instead of building it from scratch, I attempted to achieve this using OpenLayers, with the intention of using the image in place of a map. ...

What is the best way to showcase user JSON data based on the href ID?

I have JSON data saved in my main local folder and I would like to showcase user data on another page named "view.php" whenever the View User Data link is clicked with href="view.php?id=1", automatically displaying user id=1 on the view.php file. data.jso ...

Records not being filtered by the filter

I am struggling to identify records within $scope.employees that do not have a corresponding record in $scope.allEmployeeGroups. The filter does not seem to be working correctly, as it is returning all records instead of just a few unmatched ones. Despite ...

Learn how to implement a feature in your chat application that allows users to reply to specific messages, similar to Skype or WhatsApp, using

I am currently working on creating a chatbox for both mobile and desktop websites. However, I have encountered an obstacle in implementing a specific message reply feature similar to Skype and WhatsApp. In this feature, the user can click on the reply butt ...

Manipulating the InnerHTML content of a total of 144 individual cells

I am currently developing a tile-based game using tables. Each td cell contains the following code: <td> <div id="image" style="display:none; display: fixed; right: 5; top:2;"><img src="http://thumb7.shutterstock.com/display_pic_with_logo ...

Tips for updating the border color of a div upon clicking it

Currently working on a project using react/typescript and facing an issue with changing the border color and width of a div upon clicking it: <div className="showroom-card " onClick={() => setSelection({ showroom: &ap ...

As you scroll, the opacity gradually increases, creating a dynamic visual

Struggling to replicate a feature on a website where images gain opacity as you scroll down? Check out this site for reference: . While my current code somewhat achieves this effect, I'm having trouble figuring out how to apply a darker opacity gradua ...

Error Code 1305: In MySQL version 5.5.52, the function JSON_EXTRACT is not available

Issue: Unable to use json_extract due to error. The message body looks like this. < message type = "chat" to = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0730232f252d202d2b3d2c2c3f3d3d213a3d213d3a373 ...

What is the best way to export assets into a React Native JS file?

After watching a video on YouTube, I noticed that at 3:20 the individual in the video quickly exported multiple assets into a file without providing any explanation. Can someone please view this specific moment in the video and clarify how this person mana ...

Issue with file operations in Ionic1 not functioning properly after scrolling in AngularJS

Working with Ionic v1 and AngularJS, I created a file-based handheld terminal app. However, I noticed that the scroll function stopped working after performing file operations. A workaround I found is that when I click or focus on a search box, the GET re ...

Increase the Step Size of an HTML Number Input by Holding Down the Time

Is there a way to implement increasing increment/step size for number inputs in HTML based on how long the user holds the stepper arrows? For instance, starting at step size=1 and gradually ramping up to larger increments like 5, 10, 20, etc. after holdin ...

Starting the selection process using AngularJS and ng-repeat

My challenge is to have a pre-filled option in a select-box using ng-repeat with AngularJS 1.1.5. However, the select box always starts off with nothing selected and an empty option, which I don't want. It seems to be a side effect of not having anyth ...

Utilizing custom template tags with script tags for componentization within Django applications

Currently working on a Django project with multiple apps. One of the main apps serves as the base, housing global elements like CSS, JS, and custom template tags (referred to as CTTs). I'm interested in creating CTTs that contain HTML and script tags ...

Learning how to append a property to an object within an array of objects in React

Here is a state I am working with: attributes: [ {name: "capacity", items: [{ value: '256GB'},{value: '512GB'}]}, {name: 'With USB 3 ports', items: [{value: 'Yes'}, { value: 'No'}]} ] I am lookin ...

Transferring the return value from PHP to Android

I currently have a basic authentication form that is functioning correctly. Right now, it simply returns the string "success" when a login is successful and "false" when it is not. However, I would like to also return the user's data, such as their Us ...

Changing the position of an element in CSS using the center as the reference point, based on a JavaScript variable: How can it be done?

I have an image marking a scale, with the marker's position in HTML set as: <image class="red-marker" xlink:href="./assets/images/marker.png" [attr.x]=percentage width="12" height="40" y="0" ></image> But I want the middle of the marker ...

The JSON.stringify method in TypeScript/JavaScript does not align with the json-String parameter or request body in a Java controller

Currently, I am utilizing jdk 1.8 and have a rest endpoint in my Java controller: @PostMapping("/filters") public ResponseEntity<StatsDTO> listWithFilter( @RequestBody(required = false) String filter ) { try { ............... } } A test sn ...

CSS - Activating hover effects through keyframes

I'm looking to create an image effect that pulsates like a heartbeat. The idea is for the image to pulse for 3 seconds, then automatically flip for 1 second before resuming the pulsating effect indefinitely. I've managed to make the image pulse, ...

"Combining background images with javascript can result in displaying visual elements

Hello! I am in need of assistance with a CSS + Javascript fog effect that I have developed. It is functioning properly on Firefox, Opera, and Chrome but encountering issues on IE and Edge browsers. The effect involves moving two background images within a ...

Unable to access content using file_get_contents on php file

Query: $btc38="http://api.btc38.com/v1/depth.php?c=ltc&mk_type=btc"; $btc38_r=file_get_contents($btc38); $btc38_a=json_decode($btc38_r,true); I have successfully implemented APIs from other websites, but the one mentioned above is not functioning as ...