Codeigniter - how to pass JSON as a parameter to the view [duplicate] Codeigniter - how to pass JSON as a parameter to the view [duplicate] json json

Codeigniter - how to pass JSON as a parameter to the view [duplicate]


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>


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.


json_encode will return null if empty variable passed, so you no need to escape " it in you view code. instead, you have to check the variable is array or is object to pass in to generate different code.

For you example:

if( is_array( $_var_value ) || is_object( $_var_value) ){    echo 'var ' . $_var_name . ' = ' . json_encode( $_var_value ) . ";";}else{ // if( is_string( $_var_value ) ){    echo 'var ' . $_var_name . ' = "' .  $_var_value  . '";';}

Updated for you case

 <script type="text/javascript">     <?php if( is_array( $_var_value ) || is_object( $_var_value) ){ ?>     var some_data = <?php echo json_encode($some_data); ?>;     <?php }else{ ?>     var some_data = "<?php echo $some_data; ?>";     <?php } ?> </script>