Search code examples
javascriptphphighchartsarray-merge

How to use array_merge to display non-quoted commands in PHP/Highcharts?


I am passing a JSON array with multiple Highcharts arguments to the client. In a few cases, I use an array_merge to insert after the allocation code a few extra things. This works fine as long as the argument being passed will be displayed in quotes, such as:

$data_['xAxis'] = array_merge($data_['xAxis'], array("type" => "category"));

Then, on the client side, this will translate into:

type: "category"

But there are occasions, where I want to pass a function, which should be displayed like this one:

chart: {
    events: {
        load: function () {
            var label = ....
        }
    }
},    

When I use this here, it's being displayed as a text:

$data_['chart'] = array_merge($data_['chart'], array("events" => "{load: function(event) {var label = ... }}");

chart: {
    events: "{
        load: function () {
            var label = ....
        }
    }"
},    

EDIT: The Javascript on the client side looks like this:

$(document).ready(function() {
    var options = {};               

    var url =  "http://geodev.grid.unep.ch/mod_test/jsonp_response.php?callback=?";

    $.getJSON(url, {selectedCountries: selectedCountries , selectedID: selectedID, selectedYears: selectedYears, per_capita: per_capita, graphBorder: graphBorder, graphSource: graphSource, graphStyle: graphStyle, graphXAxis: graphXAxis, type: "jsonp"})
    .done(function(data)
    {
        //console.log(data);

        options.chart       = data["chart"];
        options.tooltip     = data["tooltip"];
        options.series      = data["series"];
        options.title       = data["title"];
        options.subtitle    = data["subtitle"];
        options.yAxis       = data["yAxis"];
        options.xAxis       = data["xAxis"];
        options.legend      = data["legend"];
        options.exporting   = data["exporting"];
        options.plotOptions = data["plotOptions"];
        options.credits     = data["credits"];

        var chart = new Highcharts.Chart(options);
    })

So, what can I do to pass it over in order that it is not displayed as text? Can anyone give me a hint how to do it the right way? Thanks a lot!


Solution

  • couple of ways

    1. implement event handlers in the javascript itself, like

      options.credits     = data["credits"];
      
      options.chart.events = {};
      options.chart.events.load = function(event){
          // implementations go here
      }
      
    2. Not recommending though, using eval

      options.credits     = data["credits"];
      
      options.chart.events = eval(data.chart.events);
      

    Hope this helps