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

Steps for implementing a reset button in a JavaScript slot machine game

I need assistance with implementing a reset button for my slot machine game prototype written in JS. I attempted to create a playAgain function to restart the game by calling the main game function, but it's not working as expected. Do I need to pass ...

An error was encountered: Attempting to access a method called sheetNameExists() within PHPExcel that is not

Can someone help me identify the source of this error that I'm encountering while trying to generate an excel file? Fatal error: Uncaught Error: Call to undefined method PHPExcel::sheetNameExists() in /public_html/docs/PHP/PHPExcel/Worksheet.ph ...

Utilizing PHP to Retrieve Image Information from the Imgur API

I am new to utilizing php and I am currently experimenting with the imgur API. My code is based on various tutorials, and what I'm attempting to achieve is to fetch an image from imgur and display it on a webpage. Here's the code snippet I have: ...

Symfony2 Redirecting to unauthorized page using access_denied_url

Looking to implement the access_denied_url parameter in my security.yml. The issue arises when I try to access /mon-equipement as an anonymous user, it continues redirecting me to /login. Below is my configuration in the security.yml file: security: ...

What is the best way to incorporate keyboard shortcuts into carousel operations using jQuery?

The example can be found here. I want to be able to navigate through the images using the left and right arrows on my keyboard. How can I achieve this using jQuery or CSS? This is the structure of the HTML: <div id="slider-code"> <a cla ...

Angular tabs: fetching tab content with $http upon clicking

My project involves managing big forms with a lot of data, and I've been thinking about organizing the information into tabs with separate sections for each tab. I'm looking for a solution where the content of the tabs is only loaded when clicke ...

Can you show me the method to import these ES6 exports? Are they specifically named exports or the default?

As I reviewed the code in the Material UI project, I came across a section that is exporting a variety of React Components: src/Dialog/index.js: export { default } from './Dialog'; export { default as DialogActions } from './DialogActions ...

JavaScript tabs that smoothly fade in and out

I'm currently working on implementing tabbed content, but I'm struggling with getting the fade effect to apply to the content itself when clicked, rather than just the tab headers. Check out my demo here $('#tab-wrapper li:first').add ...

Ensuring Proper Tabulator Width Adjustment Across All Browser Zoom Levels

<div id="wormGearTabulatorTable" style="max-height: 100%; max-width: 100%; position: relative;" class="tabulator" role="grid" tabulator-layout="fitDataTable"><div class="tabulator-header" role="rowgroup"><div class="tabulator-header-co ...

The HttpRequest is failing to properly interpret the header codes sent by the requested webpage

When using the HttpRequest class on a proxy to call an API, I have made modifications for caching on the API. The purpose of these modifications is to return a 304 status code if the content has not been modified, allowing the user making the request to le ...

What exactly does the question mark represent in the code structure as indicated in VSCode?

When looking at the image, you can see that in the description of done(), VSCode indicates the type of parameters using a colon error: any or sometimes with a question mark and colon user?: any. So, what exactly is the distinction between these two ways o ...

ERROR: Running out of memory in JavaScript heap while executing a command with "npm"

Encountered a fatal error (FATAL ERROR: MarkCompactCollector: semi-space copy, fallback in old gen Allocation failed - JavaScript heap out of memory) while attempting to execute any npm command. The error persists even with the simple "npm -v" command. I ...

Insert start and end tags at the appropriate locations

In my possession is a table: <div id="menu"> <table cellspacing="0" cellpadding="0" width="930"> <tbody> <tr> <td> 1 </td> < ...

Encountering an error while attempting to add class-constructed objects to an array list in React/NextJs: "Unable to add property 0, as the object is

This function contains the code required to generate rows for display in a Material Ui table. class User { constructor(id, name, email, measured, offset, paidAmount, status, home, misc, plane, transport, partner, isCoupon) { thi ...

Are there any benefits to utilizing the Mantra.js architectural framework?

I have found that integrating Meteor.js into a Mantra.js architecture works seamlessly. However, I am questioning the advantages of using it since it seems to slow down the running of my requests. For example, when making a dummy request in GraphQL (such ...

Selecting the current date in a Jquery Datepicker using PHPUnit WebDriver Selenium and PHP

Check out this demo of our datepicker: ( Located in the bottom left corner ) $search21 = $this->webDriver->findElement(WebDriverBy::id('csandbox-container')); $search21->click(); // Clicking opens the datepicker. // Now, how do I ...

Tips for Implementing the jquery.Validate Plugin with a jquery.multiselect Dropdown

Let's talk about a predicament I'm facing: trying to integrate a dropdown box into a form that already makes use of the jquery.validate plugin along with other fields that currently validate correctly. The dropdown box is being added using the jq ...

I am struggling to make jQuery function properly on WordPress

After trying multiple techniques, I am still unable to get jquery functioning properly in my custom WordPress theme. Below is a snippet of the code where I have included two different methods that I attempted, with one being commented out for reference. ...

Utilizing JQuery to display JSON data on a data table using Ajax

Seeking guidance on jQuery, I am diving into a new datatable venture with preloaded data. Upon searching, the goal is to update the table by removing existing data and displaying only the search results. My attempt so far includes: app.common.genericAjaxC ...

Choose all records that conclude at one hour

I am working with a table named konkurrencer that has a column called slutter with a datatype of datetime. How do I query and select all records from this table where the datetime value ends within 1 hour? For example, if there is a prize in the table th ...