0

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.

3
  • Ok. Do you want us to guess what format it returns or would you be kind enough to tell us/show us? Commented May 2, 2019 at 6:57
  • just remove the single quotes var services = <?php echo json_encode($services); ?>;, if you put quotes, its just treated as string literal Commented May 2, 2019 at 6:59
  • @Ghost thank you so much. I was so frustrated. You have no idea how this small thing ruined my whole night. Thank you! Commented May 2, 2019 at 7:17

1 Answer 1

2

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

var services = <?php echo json_encode($services); ?>;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.