简体   繁体   中英

Highcharts chart not loading after AJAX call to insert partial containing chart

I have rails doing a link_to ajax call from a menu to dynamically insert a chart into the main content area of my site. I can see the html is replaced correctly.. but the chart doesn't isn't loaded.

Here is the main content part of my application.html.erb:

<div id="maincontentcontainer">
    <div id="maincontent">
        <div class="section group">
            <div class="col span_1_of_7">
                <%= render :partial => "shared/menu" %>
            </div>
            <div id="replace">
                <%= yield %>
            </div>
        </div>
    </div>
</div>

Here is the index html after the AJAX call that inserts the below partial:

<div id="replace">
  <div class="col span_6_of_7">
    <section id="infographic">
      <div id="infographicContent">
        <div id="chart" style="min-width: 310px; height: 700px; margin: 0 auto"></div>
      </div>
    </section>  
  </div>
</div>

Here is the partial:

<div class="col span_6_of_7">
    <section id="infographic">
        <div id ="infographicContent">
            <%= javascript_include_tag "highcharts" %>
            <%= javascript_include_tag "charts" %>
            <div id="chart" style="min-width: 310px; height: 700px; margin: 0 auto"></div>
        </div>
    </section>  
</div>

My chart.js has all the chart has options (called options) that is passed in and run like this:

$(document).ready(function () {
        $('#chart').highcharts(options);
    });
});

Can anyone explain to me why? And what I need to do about?

Thanks.

The problem is that you are calling $('#chart').highcharts(options); before the ajax finished. So, it won't find the <div id="chart"> that wasn't inserted yet.


To resolve that issue, you have two options:

  1. Move the chart creation script to the ajax callback , to execute after ajax completion:
  $.get('domain.com/ajax_call?param=value').then(function(response) { $("#replace").html(response); $('#chart').highcharts(options); }); 
  1. Move the chart creation script to the response html after the insertion of <div id="chart"> :
 <div class="col span_6_of_7"> <section id="infographic"> <div id ="infographicContent"> <%= javascript_include_tag "highcharts" %> <%= javascript_include_tag "charts" %> <div id="chart" style="min-width: 310px; height: 700px; margin: 0 auto"></div> <script>$('#chart').highcharts(options);</script> </div> </section> </div> 

Note: I am assuming that the additional }); in your code was just a question typo/mistake.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM