Ignatius Chandra
Ignatius Chandra

Reputation: 476

Codeigniter - How to pass JSON to JS file in assets folder?

I am trying to pass json from my cotroller to my JS in assets folder

Here is my container.js :

Highcharts.chart('container', {
    chart: {
        type: 'column'
    },
    series: [{
        name: 'Umur',
        colorByPoint: true,
        data: <?php echo json_encode($based_on_age); ?>
    }],
  });

And here is my controller:

public function index(){
    $sbow=array();

    foreach ($this->m_data->based_on_weeks()->result_array() as $row) {
        $sbow[]=array($row['range'],(float)$row['total']);
    }
    $data['based_on_weeks'] = $sbow;

    $this->load->assets?(container.js,$data); //is there a way to pass data to assets?
    $this->load->view('state.html');
}

Upvotes: 1

Views: 340

Answers (2)

Agam Banga
Agam Banga

Reputation: 2693

I believe, you can simply pass your data to your view file. & you will have that data in your JS file as well. Just create a variable in your view file in script tag & it will be accessible in your `container.js' file

You can use like

var highChartData = <?php echo json_encode($data["based_on_weeks"])?>;

and in container.js, you can do

Highcharts.chart('container', {
    chart: {
        type: 'column'
    },
    series: [{
        name: 'Umur',
        colorByPoint: true,
        data: highChartData
    }],
  });

Upvotes: 3

gabe3886
gabe3886

Reputation: 4265

The way you are looking to do this won't work, as CodeIgniter is a PHP framework, and therefore runs on the server side, and the container.js file, being JavaScript is client side. Putting data/content into client side items isn't something which is done, unless you build those files and server them dynamically each time.

Along with the answer from @AgamBanga, you could also do the following directly in your view file (though you either need to include that view each time, or have it in every view you want the chart:

Highcharts.chart('container', {
    chart: {
        type: 'column'
    },
    series: [{
        name: 'Umur',
        colorByPoint: true,
        data: <?php echo json_encode($data['based_on_weeks'])?>
    }],
  });

Upvotes: 1

Related Questions