Incorporate Live Data into Google Charts Using Ajax Response for a Dynamic Visualization

I am struggling to successfully load a responsive Google Line Chart after an Ajax call. I have attempted to place the entire Google Chart code within the success part of the Ajax call, but it does not seem to work as expected. Below is my current Ajax code:

$( window ).on( "load", function() {
        $.ajax({
            url: url,
             headers: {
                    'X-CSRF-TOKEN': '{{csrf_token()}}'
            },
            type: "POST",
            data: {
                'annual_capital_growth':annual_capital_growth,
                'property': property,
                'forcast_period': forcast_period,
            },
            context: this,
            success:function(data) {
                console.log(data.graphArray); /*This is where I inserted Google Charts Code*/

            },
            error: function(errorThrown){
                console.log(errorThrown);
            }
        });
    });

Here is the Google Chart Code that I am trying to incorporate:

Please note that my code is designed to be responsive and includes additional functions for window resizing.

google.load('visualization', '1', {
  packages: ['corechart', 'line']
});
google.setOnLoadCallback(drawBackgroundColor);

function drawBackgroundColor() {
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Years');

  data.addColumn('number', 'Property Name'); 
  data.addColumn('number', 'Compute Times');
  data.addColumn('number', 'Compute Times2'); /*This is where I want to insert Ajax Data*/

  console.log("--");
  data.addRows([
    ['2018', 200000, 210000, 220000], 
    ['2019', 210000, 220000, 220000],
    ['2020', 220000, 250000, 220000], /*This is where I want to insert Ajax Data*/
  ]); 
  console.log(data);
  var options = {
    height: 350,
    legend: {
      position: 'bottom'
    },
    hAxis: {
      title: 'Years'
    },
    vAxis: {
      title: 'Property Value'
    },
    backgroundColor: '#f1f8e9'
  };

  function resize() {
    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  }
  window.onload = resize();
  window.onresize = resize;
}


Answer №1

Initially, it appears that you are utilizing an outdated version of Google Charts.
jsapi is now considered obsolete; please refer to update library loader code .

The recommended approach is to utilize the following library instead...

<script src="https://www.gstatic.com/charts/loader.js"></script>

This will only affect the load statement.


In terms of the load statement,
it automatically waits for the page to load by default,
you can replace...

$( window ).on( "load"... and $(document).ready, etc...

We recommend setting up something similar to the following...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var options = {
    height: 350,
    legend: {
      position: 'bottom'
    },
    hAxis: {
      title: 'Years'
    },
    vAxis: {
      title: 'Property Value'
    },
    backgroundColor: '#f1f8e9'
  };

  var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

  $.ajax({
    url: url,
    headers: {
      'X-CSRF-TOKEN': '{{csrf_token()}}'
    },
    type: "POST",
    data: {
      'annual_capital_growth': annual_capital_growth,
      'property': property,
      'forcast_period': forcast_period,
    },
    context: this
  }).done(function (response, status, jqXHR) {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Years');
    data.addColumn('number', 'Property Name');
    data.addColumn('number', 'Compute Times');
    data.addColumn('number', 'Compute Times2');
    data.addRows(response.graphArray);

    function resize() {
      chart.draw(data, options);
    }
    resize();
    $(window).resize(resize);
  }).fail(function (jqXHR, status, errorThrown) {
    console.log(errorThrown);
  });
});

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

Is it more effective to utilize a filter or request fresh data when filling in a form's drop-down choices?

Utilizing an axios ajax request, I am retrieving a JSON list of tags related to a specific topic selected from a dropdown. If no topic is chosen, all tags in the database (approximately 100-200 tags) are fetched. The process involves: User selects a topi ...

PHP tutorial on removing an array from a multidimensional array and creating a separate array

I'm stuck with this array: array(3) { ["cod"]=> array (3) { ["code"]=> string(3) "cod" ["title"]=> string(38) "Pay on delivery" ["sort_order"]=> string(1) "1" } ["pp_standard"]=> array(3) { ["code"]=> stri ...

Creating a wizard-like control feature in AJAX within an MVC framework

Before diving in, I wanted to get some insights on how to create a wizard-like control in ajax for MVC. The control will consist of multiple pages with data entry controls, and upon submission on each page, the entered data will be inserted into a databas ...

Which five key JavaScript concepts should I grasp in order to excel as an AngularJS developer?

Coming from a background of server-side coding, I am delving into the world of AngularJS now. This means I need to have a solid grasp of JavaScript before diving in. If I don't have enough time to master JavaScript completely at the moment, what are ...

IE 11 encountering issues with Date.parse returning NaN

Whenever I attempt to parse a date in Internet Explorer 11, it throws NaN at me. However, in Chrome and Firefox, I get the timestamp 1494559800000. Date.parse("5/12/2017 09:00 AM") The condition below is where things go wrong for me in IE 11. Is there an ...

Adding a line break in a Buefy tooltip

I am trying to show a tooltip with multiple lines of text, but using \r\n or is not working. <b-tooltip label="Item 1 \r\n Item 2 \r\n Item 3" size="is-small" type="is-light" position="is-top" animated multilined> ...

How can you use React.js to only display "Loading..." on the page while the full name is included in the URL?

I've hit a roadblock while trying to solve this issue. Here's the situation: On the page where I need to display certain information, I intended to showcase the full name of the individual from a previous form submission. However, instead of seei ...

Pull the Bootstrap radio value from hyperlink buttons

Is anyone else having trouble retrieving values of radio buttons using jQuery? Here are the radio buttons in question: <div class="input-group"> <div id="radioBtn" class="btn-group"> <a class="btn btn-warning radio-selector btn ...

What is the method for obtaining the most up-to-date JSON GET request URL?

Using JQGrid with search filters and setting loadOnce=false. I perform a search in the grid and observe the JSON request URL in firebug: http://localhost:8080/myapp/items/listGrid?ticketId=&_search=true&nd=1393573713370&rows=20&page=1& ...

Retrieve a file from a remote server without storing it locally on the server

I need to download a zip file from another server without saving it locally. Currently, I am sending a POST request to the server which responds with the zip file, then I save it on my local server and send it using res.download. What I would like is to di ...

Transferring an array between Javascript and Django

I am working with an array of objects in JavaScript, like this: Arr = [0: {k;v}, 1: {k,v}] and so on, each containing numerous fields. The challenge I'm facing is in sending these objects to Django. I have attempted using JSON.stringify to send the ...

A situation where the event onclick fails to occur within NextJS

index.js: function Home () { return <div> <html> <head> <title>Site</title> </head> <body> <div class= 'v5_3' onclick = "func_click()"></div> </b ...

Extracting data from string in object form

Values are stored as JSON objects in my database. After retrieving these values, the result is: '["{ zone :1, cat_id : 1, subcat : 2}","{ zone :1, cat_id : 2, subcat : 2}","{ zone :1, cat_id : 2, subcat : 3}"]' I then convert it to an array us ...

Guide on activating javascript code for form validation using php

How can I activate JavaScript code for form validation? I am currently implementing form validation on a combined login/register form where the login form is initially displayed and the register form becomes visible when a user clicks a button, triggering ...

Press anywhere else on the screen to dismiss the bootstrap menu

I've been attempting to find a solution for closing the Bootstrap menu when clicking outside of it in a mobile window size, but I just can't seem to make it work. I did manage to get it working when clicking one of the 'a' links using t ...

Please refer to the image located in the directory that is one level above the current location

My current setup includes an image located at images\a.jpg and a script in js\a.js. Both the images and js directories are under the www document root directory. Within the script a.js, I have the following code snippet: var provider_img = $(th ...

Having trouble understanding why ng-resource refuses to return an array

I've recently encountered an issue while using AngularJS and NGResource. For some reason, every time I try to use the query function, I receive an empty array in return. Within my controller, the code looks like this: Task = $resource('/tasks&a ...

Modify the JSON format

I have a piece of code that retrieves content from my database table. However, I need to modify the JSON output slightly. $rows = array(); if(isset($_GET['fruitName'])) { $stmt = $pdo->prepare("SELECT variety FROM fruit WHERE name = ? ORDER B ...

Implement a transition effect for the onClick event of a div element

I am looking to create a smoother transition effect when clicking on the section, causing it to expand and display the text underneath. I want to make this transition slower and more seamless. My current attempt at adding a transition to the "active" clas ...

Verify whether all the elements within a specific div are distinct by utilizing jQuery

I need to create a select box that, when an option is chosen, generates a certain number of textboxes within a div. Currently, there are three fields: display_name[], user_name[], and user_password[] The code for this functionality is as follows: <se ...