Having trouble getting the Google motion chart to work with asynchronous JSON requests

I have been using the code below to make a request for a JSON file and then parsing it.

google.load('visualization', '1', {packages: ['controls', "motionchart", "table"]});
google.setOnLoadCallback(function(){
createTable($('#chart_div').width(),400);
})
var jsonData;
$.ajax({
 url: shapingTomorrowDataUrl,
 dataType: "json",
 async: true,
 success: function(data) {
  console.log("Data done");
  jsonData=data;
  createTable($('#chart_div').width(),400);
  }
});

Initially, I used a synchronous call to the JSON file and everything worked perfectly. However, my client now wants a loading gif to be displayed while the data is being fetched. The issue with the synchronous request was that it caused the gif to hang for too long. Switching to an asynchronous request resolved this problem, but introduced another one - the chart function gets called before the JSON data has finished parsing on the first load of the dashboard.

In an attempt to address this, I modified the code to invoke the function within the success callback instead and commented out the callback function.

However, this change resulted in the following error:

Uncaught TypeError: Cannot read property 'DataTable' of undefined

Specifically, the error occurred at this line:

var chartData = new google.visualization.DataTable();

Essentially, my code only functions properly after the initial try, presumably once the JSON file is cached. On the first attempt, the loader gif keeps running without rendering the chart. Any advice on resolving this would be greatly appreciated.

Answer №1

Make sure to wait for the callback function to finish executing before initiating the $.ajax call...

var dataResponse;
google.load('visualization', '1', {packages: ['controls', "motionchart", "table"]});
google.setOnLoadCallback(function(){
  $.ajax({
   url: shapingTomorrowDataUrl,
   dataType: "json",
   async: true,
   success: function(data) {
    console.log("Data retrieval complete");
    dataResponse = data;
    createTable($('#chart_div').width(),400);
    }
  });
});

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 encountering an issue with the "z-index: -1" property in React

After creating a form placed alongside buttons, I encountered an issue where the form overlaps the buttons and prevents them from being clicked. Despite setting the z-index to -1, it seems that the form remains clickable even when not visible. Research ind ...

"Exploring the world of Angular JS through testing controllers with jasmine

I'm currently facing an issue with my test in the controllersSpec.coffee Angular App code: describe 'Controllers', -> beforeEach -> angular.module 'app' describe 'MainCtrl', -> beforeEach inject ($co ...

Struggling with understanding how to parse JSON in VB.net

Looking for some assistance. I'm grappling with parsing the JSON output provided by the cloudstack API in vb.net and feeling a bit stuck. The JSON response from the cloudstack looks like this: { "listcapacityresponse": { "count": 6, ...

Populate a dynamically created table with Json data

I have implemented a dynamic table generation feature using jQuery. Here is the code snippet: $(document).ready(function(){ // Generating table for specified number of blocks var numberOfBlocks = ${projectDetails.noOfBlocks}; var i ...

The origin of the recipient window does not match the target origin provided when using postMessage on localhost

Currently, I am in the process of developing an application that utilizes single sign-on (SSO) for user authentication. Here is a breakdown of the workflow: Begin by launching the application on localhost:3000 (using a React Single Web Application). A po ...

What is the process for retrieving information from an ajax call?

I'm looking to extract different array values from my ajax callback function. Here's what I have attempted so far: function sendFeedback() { $.post({ url: 'send-feedback.php', dataType: "json", data: { ...

Vue component not displaying object property

I am currently working on implementing a filter method in a Vue component. Here is the filter method I am trying to use: filterHotels:function(){ var thisHotels = this.hotelRoomArr; console.log(this.hotelRoomArr['107572']['rooms ...

Send a basic variable from jQuery using Ajax to Ruby

I'm a beginner in the world of Ruby, jQ, and Ajax. I always make sure to do some reading before reaching out for help. My issue is with sending a basic jQuery variable to a Ruby controller using Ajax for a seamless transition. Is it possible to pass ...

The Data Table experiences intermittent hanging issues (Table is empty) when sorting or loading data with Knockout binding

While working on a project, I encountered an issue with binding data to a table using Knockout JS and the JQuery/Bootstrap based; Data Table API. The problem was that the table would become unresponsive at times when sorted or loaded, without any errors be ...

The router component in "react-router-dom" is not functioning properly

My goal is to explicitly utilize history in my project. While I am familiar with BrowserRouter, I prefer to use Route and make history one of its properties. Upon running the program, I encounter this page: enter image description here Below is my AppRout ...

Ways to extract information from JSON files

Currently, I am working on a script to extract viewer count and follower count data from Twitch. While I have successfully retrieved the viewer count information, I am encountering issues with extracting the follower count. The essential information can be ...

React Native - Implementing asynchronous array filtering using async/await

In my code, there is a filtering method implemented as follows: _filterItems(items) { return items.filter(async item => { let isTrue = await AsyncStorage.getItem('key'); return isTrue; }) } However, when calling the method this._ ...

Execute asynchronous JavaScript request

When a user types something into the input id=2, an ajax function triggers. Here is the HTML: <input id="2" type="text" onkeyup="posttitulo(this.value)" /> And here is the SCRIPT: function posttitulo(value){ $.post("getdata/posttitulo.php",{p ...

Enhanced file uploading feature in Firefox 4 using AjaxForm

<form action="upload.aspx" enctype="multipart/form-data" id="ajaxUploadForm" method="post"> <input type="file" name="fileBase" id="fileBase"><input type="submit" value="send" /> </form> $( "#ajaxUploadForm" ).ajaxForm( { iframe: "t ...

What is the best way to insert a string into a function using PHP in this scenario?

I'm currently working on enhancing a plugin called buddypress first-letter-avatar. It currently assigns avatars based on the username's first letter, but I'd like to customize it further. My goal is to also take into account the user's ...

`In Node.js, retry attempts resulted in an HTTP 504 status code.`

I have a scenario where my http server always returns a 504 status code: const express = require('express') const app = express() app.get('/', (req, res) => { console.log('I AM HERE'); res.status(504).send('N ...

Ways to organize JSON information in Angular by date basis?

I am working on a project where I need to organize multiple JSON objects into an array based on their date data, with the date field serving as the key. ...

Create a dynamic slideshow using a bootstrap carousel in conjunction with the powerful php glob() function

I'm struggling to create a homepage featuring a slider that pulls images dynamically from a subfolder within the Wordpress uploads directory. Here's my code: <div id="" class="carousel slide" data-ride="carousel"> <!-- Wrapper for sl ...

Tips on automatically setting the default value in select2.js dropdown selection

I have integrated the select2.js library to create a dropdown list in my project. I am trying to set the default selected value for the dropdown based on the data obtained from my URL. However, I am unsure of how to achieve this using select.js. In the Ja ...

Is it possible to automatically close navigation dropdowns when the screen size changes?

I am using a bootstrap 4 navbar with dropdowns that open with CSS animation/fade-in on desktop, and a separate toggle button for mobile. Everything works fine, but when I open the dropdowns on mobile and then resize the window screen, they remain open whic ...