Welcome Guest, Not a member yet? Register   Sign In
How do I replace front-end views with JSONs in Codeigniter 3?
#6

/application/controller/Api.php
PHP Code:
<?php
defined
('BASEPATH') OR exit('No direct script access allowed');

class 
Api extends CI_Controller {
    
    public function 
index()
    {
        
$this->load->view('api');
    }

    public function 
json()
    {
        
$data file_get_contents(FCPATH.'../sampleData.json');
        
$data json_decode($data);
        
$this->output
                
->set_content_type('application/json''UTF-8')
                ->
set_output(json_encode($data));
    }


/application/views/api.php
Code:
<html>
 <head>
   <!--Load the AJAX API-->
   <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
   <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
   <script type="text/javascript">
   
   // Load the Visualization API and the piechart package.
   google.charts.load('current', {'packages':['corechart']});
     
   // Set a callback to run when the Google Visualization API is loaded.
   google.charts.setOnLoadCallback(drawChart);
     
   function drawChart() {
     var jsonData = $.ajax({
         url: "/index.php/api/json",
         dataType: "json",
         async: false
         }).responseText;
         
     // Create our data table out of JSON data loaded from server.
     var data = new google.visualization.DataTable(jsonData);

     // Instantiate and draw our chart, passing in some options.
     var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
     chart.draw(data, {width: 400, height: 240});
   }

   </script>
 </head>

 <body>
   <!--Div that will hold the pie chart-->
   <div id="chart_div"></div>
 </body>
</html>

/sampleData.json
Code:
{
 "cols": [
       {"id":"","label":"Topping","pattern":"","type":"string"},
       {"id":"","label":"Slices","pattern":"","type":"number"}
     ],
 "rows": [
       {"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
       {"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
       {"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
       {"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
       {"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
     ]
}
Reply


Messages In This Thread
RE: How do I replace front-end views with JSONs in Codeigniter 3? - by jreklund - 08-21-2019, 10:11 AM



Theme © iAndrew 2016 - Forum software by © MyBB