Search code examples
javascriptphphtmlhighmaps

How to make multiple charts using highcharts in a loop?


This is the relevant code I have:

        <script>
            titles = <?php echo json_encode($graphTitles)?>;
            //Loop through the graphs
            for (var graphNO = 0; graphNO < titles.length; graphNO++)
            {                               
               //CREATE NEW CONTAINER
                var container = document.createElement('div'); 
                document.body.appendChild(container);er);

                dates = <?php echo json_encode($recivedDates);?>[titles[graphNO]];
                //I EXTRACT A FEW  MORE ARRAYS THE SAME METHOD
              $(function () 
                {
                  $(container).highcharts({
                      title: {
                          text: titles[graphNO]
                      },
                      xAxis: {
                          categories: dates
                      },
                      series: [{
                          type: 'column',
                          color: 'gold',
                          name: 'Created Issues',
                          data: createdIssues.map(Number)
                      }, 
                       //MORE COLUMN'S AND SOME SPLINES. IT ALL WORKS AS EXPECTED
                  });
                });
            }
        </script>

I didn't want to post all the code and just make it messy, what I expected this code to do is:

graphNO has the value of 2, I thought it would loop through twice (which it does), make a container for each loop (which it does), then draw a different graph for each loop it does in the container it just made (but instead it just draws the second graph).

I don't know whats wrong, but any ideas on how to fix this, or any ideas on how to make multiple graphs in a loop would be great help.

Also, this is the first site I'm making so I haven't used javascript, php, or html for more then a day, so sorry if it's really obvious, I couldn't find anything on this though.


Solution

  • I got it, after a day of trying complex stuff from around the web that didn't work, I ended up thinking what will happen if I remove the function so rather then:

                 $(function () 
                {
                  $(container).highcharts({
                      title: {
    

    I just have:

                  $(container).highcharts({
                      title: {
    

    And it all worked perfectly. I don't know why, probably because of how jquery deals with functions, I don't know, I didn't even know what I was using was jquery till an hour ago. But it works if anyone ever wants to do something similar, it works, and feel free to tell me why.