Skip to content

PHP Variables to JavaScript Variables in CodeIgniter

Last updated on December 2, 2022

Often, you’ll find yourself in situations, where you want to pass some server-side string/array/whatever to your JavaScript. Traditionally, this can be a bit of a pain – especially as your app grows.

Transform PHP Vars to JavaScript” is a CodeIgniter library and it simplifies the process drastically. And it is developed based on “PHP-Vars-To-Js-Transformer” it is developed by JeffreyWay.

PHP Variables to JavaScript Variables in CodeIgniter

How to install

Download the files add put PHPtoJS.php class in your library folder application\libraries\PHPtoJs.php. Now load the library locally or globally.

Locally

  $this->load->library('PHPtoJS');

Globally

Open your autoload.php file which is located at application\config\autoload.php

$autoload['libraries'] = array('PHPtoJS');

After loading the library, you may use your controllers as shown below.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {


    public function index()
    {
         $this->load->library('PHPtoJS',['namespace' => 'arjun']);
            $this->phptojs->put([
                'foo' => 'bar',
                'age' => 29
            ]);

        $this->load->view('welcome_message');
    }
}

Final step – in your layout page or view page add this line, which will print the JavaScript variables.

 echo $this->phptojs->getJsVars(); 

That is it.

0 0 votes
Article Rating
Subscribe
Notify of
guest

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments