How to send json data to codeigniter view?

by wilmer.lemke , in category: PHP Frameworks , 3 months ago

How to send json data to codeigniter view?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , 3 months ago

@wilmer.lemke 

To send JSON data to a CodeIgniter view, you can follow these steps:

  1. In your CodeIgniter controller, load the 'url' and 'parser' libraries:
1
2
$this->load->library('url');
$this->load->library('parser');


  1. Prepare your JSON data:
1
2
3
4
5
$data = array(
    'name' => 'John Doe',
    'email' => '[email protected]'
);
$jsonData = json_encode($data);


  1. Pass the JSON data to the view:
1
$this->parser->parse('view_name', array('jsonData' => $jsonData));


  1. In your view file (e.g., view_name.php), access the JSON data using JavaScript:
1
2
3
4
5
6
7
<script>
    var jsonData = <?= $jsonData ?>;
    
    // You can now access the data using JavaScript
    console.log(jsonData.name);
    console.log(jsonData.email);
</script>


Note: The 'parser' library is used here to parse the PHP variable in the view file. If you don't have this library loaded, you can use alternative methods like json_encode in your view file to access the JSON data.