nicholas79171
nicholas79171

Reputation: 1273

Why doesn't HighCharts render when I pull it in with Ajax?

I have a chart that loads just fine at the path /charts/chart1. To separate the long load times of the chart with the rest of the webpage, I'm using Ajax to load in the chart. Here's the code I'm using:

$(function() {
  $.ajax({
    type: 'GET',
    url: '/charts/chart1',
    success: function(response) {
      $('#firstChart').append(response);
    }
  });
});

However, the chart is not loaded in to the #firstChart <div>. The id of the actual div at /charts/chart1 is #chart1.

I've tried reloading the chart by adding the following code:

chart1 = $('#chart1');
options = chart1.highcharts().options;
chart1 = new Highcharts.chart(options);

When running this code in the console on /charts/chart1, I reload the exact same chart. However, when running this on on the page that made the Ajax call, I get the error Uncaught TypeError: chart1.highcharts is not a function. Also, Highcharts.charts in the console returns an empty array, meaning the chart is not being pulled with the Ajax request.

Why does the chart load fine when going to /charts/chart1, but the chart doesn't load when loading via Ajax?

Upvotes: 1

Views: 620

Answers (1)

Sean Fahey
Sean Fahey

Reputation: 1910

Make sure that your Highcharts library is being loaded on the page making the AJAX request. You don't need to load Highcharts on /charts/chart1 unless you are looking to also make that page available to stand alone. The important thing /charts/chart1 needs to supply is the data inside $('#chart1').highcharts({ ... }); that will tell the Highcharts library how to render your chart on the page making the AJAX request.

In fact, loading the Highcharts library on both /charts/chart1 and on the page making the AJAX request will probably give you Highcharts Error #16 because Highcharts is being loaded multiple times.

Otherwise your AJAX function is correct, and I was able to make it work for me on localhost with an example Highchart. If you still have issues, double check that your /charts/chart1 path really does return the Highcharts data to the requesting page.

Upvotes: 1

Related Questions