Graph only displays data after button is clicked

I have been working on customizing this jsfiddle to display database data. Check it out here: http://jsfiddle.net/jlbriggs/7ntyzo6u/

Using JSON, I am fetching data from my database and editing chart1 to display the database data:

var chart,
  chartOptions = {},
  chartData = {};

chartData.chart2 = randomData(10, true);
chartData.chart3 = randomData(65, true, 300);

chartOptions.chart1 = {
  chart: {
    type: 'column'
  },
  title: {
    text: 'Chart 1 Title'
  },
  xAxis: {
    categories: []
  },
  yAxis: {
    title: {
      text: 'Chart 1<br/>Y Axis'
    }
  },
  series: [{
    name: 'Chart Series',
    data: []
  }]
};
var tableName = '<?php echo $tableName; ?>'
$.getJSON("../../companies/charts/Data.php", {id: escape(tableName)}, function(json) {
    chartOptions.chart1.xAxis.categories = json[0]['data'];
    chartOptions.chart1.series[0].data = json[6]['data'];
});

The issue I'm facing is that the chart appears empty when the page loads. The data only shows up when I click the chart1 button. Any idea why this is happening after setting the xAxis and series data?

Since $.getJSON is asynchronous, I attempted using ajax to send the request. However, the chart now doesn't display any data, even upon clicking the 'chart1' button:

chartOptions.chart1 = {
  chart: {
    type: 'column'
  },
  title: {
    text: 'Chart 1 Title'
  },
  xAxis: {
    categories: []
  },
  yAxis: {
    title: {
      text: 'Chart 1<br/>Y Axis'
    }
  },
  series: [{
    name: 'Chart Series',
    data: []
  }]
};
var tableName = '<?php echo $tableName; ?>'
$.ajax({
  url: "../../companies/charts/Data.php",
  data: {id: escape(tableName)},
  dataType: "json",
  async: false,
  success: function(data) {
  chartOptions.chart1.xAxis.categories = json[0]['data'];
  chartOptions.chart1.series[0].data = json[6]['data'];
  }
});

Thank you for your help in advance!

Answer №1

It seems like the issue here is that the asynchronous nature of $.getJSON causes the chart to load before the data is inserted. To fix this, you can try calling the setData method on the series inside the $.getJSON block to force a redraw of the chart:

chartOptions.chart1.series[0].setData(json[6]['data'],true);

Alternatively, you could make the request synchronous using $.ajax with async:false. Replace the existing code block with the following:

$.ajax({
  url: "../../companies/charts/Data.php",
  data: {id: escape(tableName)},
  async:false
}).done(function() {
  chartOptions.chart1.xAxis.categories = json[0]['data'];
  chartOptions.chart1.series[0].data = json[6]['data'];
});

These adjustments should help resolve the issue.

For more information, check out: jQuery.ajax documentation

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

Error encountered: Mocha - The property '$scope' cannot be read as it is undefined

I encountered an issue: Error: Type Error - Cannot read property '$scope' of undefined at $controller (angular/angular.js:10327:28) at angular-mocks/angular-mocks.js:2221:12 at Context. (src/client/app/peer-review/post-visit.co ...

"Create dynamic web pages with multilingual support using HTML, JQuery, and nested

For my multilingual website, I wrote this simple JQuery code: (function() { var language, translate; translate = function(jsdata) { $('[tkey]').each(function(index) { var strTr; strTr = jsdata[$(this).attr('tkey')] ...

What steps can be taken to address the error message "FATAL: Unable to load template" encountered while using

I'm encountering the issues documented here and here on GitHub. I'm working on incorporating documentation for my Next.js code, and below is my jsdoc configuration file. { "tags": { "allowUnknownTags": true, "di ...

Utilize INNER JOIN combined with JSON to retrieve $numrows from the database

Currently, I am working on getting the JSON data to display a specific number of comments for a post in order to automatically update the feed that I have developed. In order to achieve this, I need to combine the 'STREAMDATA table' and the &apos ...

Using Gradle: Leveraging the output file data of one task for another task

Challenging Situation I need to update HTML files before packaging them in a WAR file to include a HASH variable that corresponds to a JS bundle compilation. This is the current situation: <script th:src="@{/static/js/assistance/manifest.js}" charset ...

Error: The document object is not defined when attempting to access it within a

<script type="module" src="/scripts/navbar.js"></script> <script> async function fetchContent(e) { e && e.preventDefault(); const response = await fetch('https: ...

Error: The function sendFile does not exist in the method res.status(...)

As a newcomer to this field, I must apologize if my issue has an obvious solution. However, I am encountering the following error: TypeError: res.status(...).sendFile is not a function at app.get (/root/discordtest/server.js:10:19) at callbacks (/ ...

Guide on displaying multiple views along with their respective models fetched through AJAX in Backbone

Hey there! I'm currently working on painting a screen with multiple models and associated views in backbone. To achieve this, I have separate ajax calls to fetch data for these views. Initially, I thought using the jQuery function $when(ajaxcall1, aja ...

Learn how to send dynamic data to another HTML element using Ajax's success function

I received a successful ajax response from one HTML file, but I'm struggling to dynamically set the data from this response to another HTML file. Can anyone help me with this issue? Here is the code snippet from my ajax report: success: function( ...

Can Child Component Changes in React Checkbox Cause Parent Node to Re-Renders?

Struggling with creating checkboxes for my project, I've spent an entire day on it without finding a solution. The issue involves a main checkbox that controls all child checkboxes. The desired functionality is to have the parent node's "allChec ...

Ways to stop React from refreshing the page upon clicking the submit button

Is it possible to prevent a React component from reloading the page when a submit button is pressed? Here is an example of component code: class MyComponent extends React.Component<IEditCampaignStateProps & IEditCampaignDispatchProps, EditCampaignStat ...

What is the process for deleting certain code from a main component within a React webpage without altering the main component itself?

I have a main component named Layout.jsx that includes the essential elements for the website such as the navigation bar and meta tags. It also contains a Google tag to track analytics across the entire site. Now, I have a specific webpage for Google Ads w ...

Why is the ionChange/ngModelChange function being triggered from an ion-checkbox even though I did not specifically call it?

I have an issue with my code involving the ion-datetime and ion-check-box. I want it so that when a date is selected, the checkbox should automatically be set to false. Similarly, if the checkbox is clicked, the ion-datetime value should be cleared. Link ...

Transforming Javascript code using regular expressions into C#

Currently, I am facing a challenge while trying to translate some Javascript code into .NET. Despite my efforts, I have not been able to get it right. The task at hand involves converting paths like /test/:value1/:value2 in Express for NodeJS to a regular ...

Is it possible to alter the page color using radio buttons and Vue.js?

How can I implement a feature to allow users to change the page color using radio buttons in Vue.js? This is what I have so far: JavaScript var theme = new Vue({ el: '#theme', data: { picked: '' } }) HTML <div ...

Tips for exporting and importing Blender 3D meshes with animations using JSON format and loading them into Three.js version r90

Does anyone know how to import a mesh with animation from Blender 3D animation to JSON and load it using Three.js version 90? I'm having trouble getting this to work. loader.load( 'models/fox/fox_run.json', function ( geometry, materials ...

Executing a function on each page within the head tag in Nuxt.js

I successfully made my function accessible by using the plugin attribute in the nuxt.config.js file, allowing me to call the function under mounted on every page. I am looking for a more efficient way to run this function within the head tag and have it b ...

Is there a way to shade the entire webpage background in HTML?

Instead of affecting other DOM classes, I tried using another div but it doesn't darken the whole page. This means I have to manually modify each DOM class. Is there a way to overlay the entire document with a semi-transparent gray plane? ...

Utilizing TypeScript Class Inheritance: The Reference to 'super' is Only Allowed in Members of Derived Classes or Object Literal Expressions

We have encountered a scoping issue while using TypeScript classes with inheritance. It seems that TypeScript/JavaScript does not allow us to use 'super' within a promise structure or an enclosed function. The error message we are getting is: Ty ...

Is there a solution to resolving the type error that I am unable to identify?

I am attempting to implement a custom cursor feature in Vue 3, but unfortunately my code is not functioning as expected. Below you can find the code snippet I have been working on: <template> <div id="cursor" :style="cursorPoi ...