Codeigniter - how to pass JSON as a parameter to the view

12,712

Solution 1

Your JSON values was not getting pass to the view, try corrected following code.

public function index()
{
    $some_data = $this->Some_model->get_some_data();
    $some_data = json_encode($some_data);
    $data = array (
            'some_data' => $some_data
    );
        $this->load->view('some_view',$data);

}



//in view file 
   <script type="text/javascript">
     var jsonData = <?php echo $some_data; ?>
   </script>

Solution 2

This can be done safely without a lot of code, provided that you have some sanity in your model. The JSON you posted leads me to believe that you have a database containing events, and an event either exists or it doesn't.

If $this->Some_model->get_some_data() returns a typed FALSE or NULL that can be verified with the equality operator if no results exist, you can safely express this to your JS in the view in the same way that you could convey the JSON.

E.g:

$some_data = $this->Some_model->get_some_data();
if ($some_data === NULL) {
     $data['somedata'] = 'null';
} else {
     // We trust our model, pass it along.
     $data['somedata'] = json_encode($some_data);
}
$this->load->view('some_view', $data);

Then, in your JS, simply verify that the variable that would contain the raw JSON string is in fact not null prior to operating on it. You could also just set it as an integer, the point is make it easy to differentiate.

From the looks of it, if event(s) actually exist, you'll at least have the event data and the person creating it as a member. You may need to do more sanity checking than that, I'm not sure what's in your model.

Just make sure the PHP variable is expanded in a syntactically correct way within your JS, or perhaps elect to alter the JS entirely if no data exists to feed it.

Share:
12,712

Related videos on Youtube

user898836
Author by

user898836

Updated on June 25, 2022

Comments

  • user898836
    user898836 almost 2 years

    I'm building a codeigniter/php web application. I'm trying to pass a JSON object from the controller to the view when the view is loaded, in a way that it will be accessible to the javascript.

    The JSON looks like the following:

    {
        "event": {
            "id": "1",
            "name": "Some name",
            "description": "Some description",
            "address": "1 Main st."
        },
        "members": {
            "others": [
                {
                    "id": "26",
                    "name": "Brad Black"
                },
                {
                    "id": "27",
                    "name": "Bill Blue"
                }
            ],
            "current": {
                "id": "1",
                "name": "Jill White"
            }
        }
    }
    

    The controller code looks like the following:

    public function index()
    {
        $some_data = $this->Some_model->get_some_data();
    
        $some_data = json_encode($some_data);
    
        $data = array (
                'some_data' => $some_data
        );
    
        $this->load->view('some_view',$data);
    }
    

    The view (some_view) code looks like the following:

    <script src="path/to/scripts/some_script.js" type="text/javascript"></script>
    
    <script type="text/javascript">
    
        some_data = "<?php echo $some_data?>";
    
    </script>
    
    <div class="main">
    </div>
    

    The javascript (some_script) code looks like the following:

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

    The challenge is that since the JSON object is sent as a string (after json_encode) it has characters such as { and quotes as part of it, which the javascript does not like when I'm assigning it to a var (some_data = "";). I've tried using also but it does not work as well.

    I tried doing a bunch of things which did not work, in order to make progress I temporarily ended up replacing the " in the controller $data['some_data'] = str_replace('"', """, $some_data);

    public function index()
    {
        $some_data = $this->Some_model->get_some_data();
    
        $some_data = json_encode($some_data);
    
        $data = array (
                'some_data' => str_replace('"', "&quot;", $some_data);
        );
    
        $this->load->view('some_view',$data);
    }
    

    and replacing the " back to " inside the javascript some_data = some_data.replace(/"/g, '"');

    var some_data;
    
    $(document).ready(function(){
    
        event_data = event_data.replace(/&quot;/g, '"');
        some_data = $.parseJSON(some_data);
    });
    

    This is kind of ugly and i'm looking for a better solution.

    Any pointers will be greatly appreciated.

    Update! Problem solved, looks like extra quotes were breaking things.

    The solution is inline with mohan.gade's answer:

    Controller:

    public function index()
    {
        $some_data = $this->Some_model->get_some_data();
    
        $some_data = json_encode($some_data);
    
        $data = array (
                'some_data' => $some_data;
        );
    
        $this->load->view('some_view',$data);
    }
    

    View:

        some_data = <?php echo $some_data?>;
    
    </script>
    
  • user898836
    user898836 over 11 years
    Thanks Cauliture. Are you suggesting I should use your code inside a <?php ?> instead of my <script type="text/javascript"> some_data = "<?php echo isset($some_data) ? $some_data : ''?>"; </script>
  • Cauliturtle
    Cauliturtle over 11 years
    No, it may ugly in view file, but I think it is easy to read and maintain and also good handle on javascript.
  • user898836
    user898836 over 11 years
    Thanks mohan, I'm actually doing it as you suggested in the right order, when I wrote the question I cut and paste the lines in the wrong order. The JSON is created correctly, my problem is how to assign it to a javascript var on the client side (view/javascript). I've updated the question to reflect it.
  • user898836
    user898836 over 11 years
    Your code worked well! It looks like I had (for some reason) an extra quotes around the <?php ?> tag... Marked your answer as the correct one
  • mickmackusa
    mickmackusa over 4 years
    The isIterable condition is not necessary. stackoverflow.com/a/57439636/2943403