What is the process for assigning values once the Google Charts program has completed its drawing?

It might sound strange, but I have a piece of code here:

let globalResult = [];
let defaultData = ["None", 1200, 1200, 1200, 1200, 1200, 1200, 1200,
1200, 1200, 1200, 1200];
$(document).ready(() => {
    // add a listener to the textbox
    $('#input').on("change", (evt) => {
        let text = $('#input').val();
        // sending a parameter named text with the entered value from the textbox
        $.get("/display", {text: text})
            .done((data) => {
                globalResult = data['result'];
                $('#input').val('');   // reset the textbox
                
                google.charts.load('current', {'packages':['corechart']});
                google.charts.setOnLoadCallback(drawChart);

                function drawChart() {
                    var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

                    chart.draw(data, options);
                    defaultData = globalResult;
                }

            })

I attempted to swap defaultData and globalResult after drawing the Chart, however, it consistently draws a new chart when data is swapped, causing interruptions in the graph rendering. If I move this outside the function drawChart, it ends up drawing two identical lines with one abruptly ending midway. Placing this outside the $.get() scope also doesn't work as the chart fails to be drawn. How can I resolve this issue?

Answer №1

When using the load statement (google.charts.load), it will wait until the document is fully ready before executing the callback or promise it returns. This eliminates the need for $(document).ready.

Start by loading Google using a promise, then create the chart and save the reference for future use. This approach allows you to draw the same chart with different data.

For a recommended setup, consider something similar to the following:

let globalResult = [];
let defaultData = ["None", 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200];
google.charts.load('current', {
  packages: ['corechart']
}).then(() => {
    // Save reference to the chart here
    var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
    
    $('#input').on("change", (evt) => {
        let text = $('#input').val();
        $.get("/display", {text: text})
            .done((data) => {
                globalResult = data['result'];
                $('#input').val('');
                
                // Chart functionality....
                chart.draw(data, options);
                
                // Swap values here
                defaultData = globalResult;
            });
    });
});

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

Changing Background Color on Div Click

After spending a considerable amount of time on this, I find myself getting confused and stuck. It seems like I might be overlooking something crucial. Essentially, my code is designed to have the default div background (gamebg), and upon clicking one of t ...

Continuously update in JavaScript based on a condition, cease updating when the condition no longer

I have a scenario on my page where specific data needs to be refreshed every minute, but at the same time, the user should be able to view and edit certain modals. I want to ensure that when a modal is open, the data refreshes are paused so that the modal ...

Ways to merge values across multiple arrays

There is a method to retrieve all unique properties from an array, demonstrated by the following code: var people = [{ "name": "John", "age": 30 }, { "name": "Anna", "job": true }, { "name": "Peter", "age": 35 }]; var result = []; people. ...

Compatibility issues between jQuery and AngularJS are causing problems

Currently, I am facing a compatibility issue between RequireJS and Angular in my setup. Everything functions without any problems when using jQuery version 1.7.2. However, I wanted to upgrade to jQuery 1.8.1 along with jQuery UI, but unfortunately, my Angu ...

Java - Define the data fields to retrieve in a RESTful API

I am currently working on implementing REST based services in Java, and I'm facing a challenge with returning the full entity in JSON for each GET call. The code snippet I have at the moment is as follows: @GET @Path("movie/{id}") @Produces({"applic ...

What is a dynamic component in Vue with Typescript?

I need help implementing type checking for my dynamic component instead of relying on 'any' as a workaround. Can someone guide me through the proper way to achieve this? <script> ... interface { [key: string]: any } const pages: page = ...

Exploring the world of nested routes and AJAX in Rails 3.2

Working with Ruby on Rails 3.2, I've built a basic test blog application featuring a Post model and a Comment model. The relationship is such that a post has_many :comments while a comment belongs_to :post. My routes.rb file looks like this: resourc ...

The input given to Material UI autocomplete is incorrect, even though the getOptionSelect parameter already exists

I'm currently working on creating my own version of the Google Places autocomplete found in the Material UI documentation. While I have successfully implemented the autocomplete feature and am able to update my component's state with the result, ...

"Create a React button component that, when clicked, navig

I'm currently developing a web application using React and bootstrap. I'm facing difficulties in redirecting the page to another one when applying onClick to buttons. After adding a href, I'm unable to navigate to another page. Do you think ...

Converting JSON data into a CSV file with various columns

When I convert my json data to a csv file using the pandas method df.to_csv('codetocsv.csv', index=False), the resulting csv file combines the entries in my 'series' column into a single column. I am aiming to separate each string into ...

Dealing with intricate query parameters in Express.Js

Currently, I am working on developing REST APIs using Express.js. One particular express route that I have set up is as follows: /api/customer I have incorporated multiple query parameters into this route, such as: /api/customer?name=jake /api/customer?c ...

Using Jquery Ajax to validate login information by submitting an HTML form

Working on a project involving jQuery Ajax, HTML forms, MySQL, and PHP. I have a database with registered users and I want to use a login form to retrieve user information from the database upon submission. However, I'm encountering an issue where the ...

Tips on running methods consecutively within ngOnInit in Angular

I'm currently working on an ngoninit function that contains four methods. Two of these methods are responsible for retrieving data from the API, while the other two are intended to load this data when the page loads. ngOnInit(){ getname(); getsubjects ...

React-file-viewer shrinks any document to a compact size

I have been searching extensively for information on how to adjust file sizing in react-file-viewer without any success. My objective is to utilize the react-file-viewer to allow users to click on a filename hyperlink and open the file (be it an image, do ...

Activating a button by pressing the Enter key using JQuery

$("#AddDataStavka, #AddDataRazmer").on("keyup", function (event) { if (event.keyCode == 13) { e.preventDefault(); $("tr.trNewLine").children().first().children().first().get(0).click(); } }); /* I'm trying to execute this ...

Creating a function to add new entries to a dictionary in R

I'm looking to translate the code below into R, but I'm unsure of how to proceed: def add(args): result = args["a"] + args["b"] return result The reason for this is that on the platform I am using (Cloudera Data Science W ...

Firebase allows for the updating of an object within a nested array

Within Firestore, I have a Document that includes a property named "items" which is of type array. This array consists of ShoppingItem objects with the specified structure: export class ShoppingItem { id?: string; name: string; checked = false; } To ...

Transforming data from PHP JSON format into HTML output

Struggling to convert JSON data into HTML format? Having trouble maintaining the correct order of child elements in your structure? Here's a solution: Take a look at this example JSON: { "tag": "html", "children": [ { "ta ...

real-time update of gauge value from soap

I am trying to update the value shown in my justgage widget with the value returned from $("#spanrWS_Measured").text(data[0]);. The current value is 123. Any assistance would be greatly appreciated. See the complete code below. <script src="scripts/r ...

Get a set of numeric values in PHP encoded in JSON format

I am trying to extract an array from the JSON data obtained in my PHP script. In my Android application, I retrieve the JSON string from a URL like this: JSONObject json = jParser.makeHttpRequest(url_all_user, "GET", paramstodb); To fetch the phone numbe ...