Nick.K
Nick.K

Reputation: 398

How to convert a json encoded php variable to a JavaScript JSON object in the same file

I am integrating codeigniter with React for purposes of server side rendering. I am having trouble converting json encoded data to a javascript JSON object. The data is an array of objects.

When I try to JSON.parse it I get Unexpected token in JSON error.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html> 
<html lang = "en"> 

<head> 
<script crossorigin 
src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react- 
   dom.development.js"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/babel- 
standalone/6.26.0/babel.js"></script>
  <meta charset = "utf-8"> 
  <title>CodeIgniter View Example</title> 
  <style>
  .header{
    background-color:'#000';

  }
  h1{
    color:'white';
  }
  </style>
</head>

 <body> 
  <?php $this->load->view('templates/header'); ?> 


 <div id = 'root'>

  </div>

   </body>
<script type="text/javascript">
   var services = '<?php echo json_encode($services); ?>';
   console.log(services);
 </script>
</html>

The code outputs a string with all the data but not in a JSON format.

Upvotes: 0

Views: 885

Answers (1)

madalinivascu
madalinivascu

Reputation: 32354

Remove the quotes around the php, you want a js object not a string

var services = <?php echo json_encode($services); ?>;

Upvotes: 2

Related Questions