0

I'm using Codeigniter and Smarty (template engine) and therefore using templates.

I have a method that calls the template which has all html, css and js functions:

public function index()
{
    //dashboard text
    $this->data['title'] = 'Dashboard';
    $this->data['subtitle'] = 'feeds, users, and more';

    //load the donut graph data
    $fbyg = $this->feed_model->countFeedsByGroups();
    echo json_encode($fbyg);

    //parses the dashboard template
    $this->smartyci->display('dashboard.tpl', $this->data);
}

the thing is that I need to send some information to one of the js files bounded to my dashboard.tpl in order to render a graphic.

So I know I have to encode the php array into jSon object and send it to the template. But, how do I do this when I have not only to send and echo with the json but also I have to display my template sending for it other information?

The other question is, How do I receive the json and get the data? I'm trying and so far no results:

From my dashboard.tpl:

    <script src="{site_url()}application/views/js/test.js"></script>
    <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>

From test.js:

$.getJSON('admin.php', function(data) {
    console.log(data.vgro_name);
});    
Limon
  • 1,772
  • 7
  • 32
  • 61
  • Don't use `echo`, but **return the string instead**, so you will be able to use it whenever you want now. – romuleald Apr 21 '15 at 14:42
  • you mean I should put it in a variable like $this->data['jsondata'] = json_encode($fbyg) ? how do I access to this data in the function? – Limon Apr 21 '15 at 14:47
  • remove `echo json_encode($fbyg);` and add `return json_encode($fbyg);` at the **end of your function**, so you could to `echo index()` or `$data = index();` then use it how you want. – romuleald Apr 21 '15 at 14:49

1 Answers1

0

You could set it like

$this->data['fbyg'] = json_encode($fbyg);

And then in your javascript do

var yourVar = <?php echo $fbyg ?>;

A cleaner solution would be to make an ajax call to a function that will return something like

$fbyg = $this->feed_model->countFeedsByGroups();
echo json_encode($fbyg);

after the page has loaded.

Edit jQuery ajax get:

$.ajax({
  type: "GET",
  url: "urlToYourFunction",
  success: function(data){
     var yourVar = data;
  }
});

I've only ever made get and post requests with angularjs and jquery, but here's another stackoverflow post detailing how to do it with regular javascript:

https://stackoverflow.com/a/18078705/3739551

I hope this helps!

Community
  • 1
  • 1
Jeremy Jackson
  • 2,247
  • 15
  • 24