Passing PHP variables to JavaScript

I was involved in a project this December where, in order to simplify the code and due to some ill-conceived piece of code, it was required to pass some variables from PHP to JavaScript. On other projects you may need to pass arrays or localized text to your JavaScript, for example to show messages. Or to fill a dinamic interface.

There are multiple ways to pass data from PHP to JavaScript: populating hidden inputs or writing the JavaScript into the main page. But I wanted to have a more clean approach.

So, I subclassed a class I wrote some time ago as an utility for handling interface configurations to handle those JavaScript globals without having to worry about the problem in each project. As a result now I have a set of three classes to ease the coding of both configuration strings and JavaScript globals. In appearance very disparate problems, but that use the same basis: magic PHP methods.

What are those magic methods? Some special methods defined in PHP 5.x that are executed automagically for certaind parts of your code. For example, one of the most used magical method is __construct(), the constructor method. All of the magical methods start with ‘__’, such as __get() or __set(), that are two of the methods used in this classes. You can look at the use of each method on The most important method in this classes is __toString(), that is called automatically each time you echo or print and object and… you guessed it, returns a string.

So I created an object with an empty array. Each time you call $object->aName it will add an “aName” element to that array, by way of the __set() method. In the __toString() method I “foreach” the array and write the name and the value of each member in the array. To JSON or to JavaScript. Cool, right?

For example, this code:

$objJS = new jsGlobalsClass();

// I want the vars ordered alfabetically

// some numbers
$objJS->numContactID = $numRecordID;
$objJS->numCustomerID = $numCustomerID;

// an array to dinamically create a select in my JavaScript code
global $gArrDirecciones;
$objJS->arrDirs = array();
foreach($gArrDirecciones as $key => $label){
$objJS->arrDirs = array(‘ID’ => $key, ‘LABEL’ => $label);

// some int’l texts
$objJS->textHelp = $objJS->text($TEXTOS[‘texto_help’]);
$objJS->textConfirmEdit = $objJS->text($TEXTOS[‘text_confirm_edit’]);
$objJS->textConfirmDelete = $objJS->text($TEXTOS[‘text_confirm_delete’]);
$objJS->reglaNombre = ‘”required,nombre,’ . $ERROR[‘rsv_nombre’] . ‘”‘;

// write the vars
echo $objJS;

Will generate this JavaScript.
var    arrDirs = {“0″:{“ID”:”1″,”LABEL”:”Sede central”},”1″:{“ID”:”2″,”LABEL”:”Envíos”},”2″:{“ID”:”3″,”LABEL”:”Facturación”},”3″:{“ID”:”4″,”LABEL”:”Sucursal”}},
numContactID = 2323,
numCustomerID = 998,
reglaNombre = “required,nombre,El campo nombre es obligatorio.”,
textoAyuda = “Sit&uacute;e el cursor sobre el icono, bot&oacute;n o campo para el que desee obtener ayuda.”,
textoConfirmDelete = “\u277Est\u341 seguro que desea eliminar este [[1]]?”,
textoConfirmEdit = “Est\u341 editando un [[1]].\n\u277Est\u341 seguro de que quiere cancelar la edici\u363n y mostrar otro en su lugar?”;

So, you’ve cleanly written some JavaScript code directly from your PHP variables.

Now, once you start to code you cannot stop. You know how it is. So I wrote a third class. This one to join several JavaScript files into one. Since it’s a descendant of jsGlobalsClass it will also add, to the beginning of the joined file, any global that you have magically “__set” to the class.

$objJSLoad = new jsLoaderClass();

$objJSLoad->setOutput($GLOBALS[‘MODULE_PATH’] . ‘_dom/cliente.js’);

$objJSLoad->addFile($GLOBALS[‘BASE_PATH’] . ‘_dom/code.comms.js’);
$objJSLoad->addFile($GLOBALS[‘MODULE_PATH’] . ‘_dom/code.js’);

$objJSLoad->numContactID = $numRecordID;
$objJSLoad->numCustomerID = $numCustomerID;

<script type=”text/javascript” src=”./_dom/cliente.js”></script>

In the resulting file you’ll have the content of code.comm.js (a library for all modules), code.js (the specific functions for this module), plus a couple of global variables. Clean code, with all the needed data, in just one file to send to the browser.

Some other day I’ll write about a couple of interesting things you can do with the parent class, opcionesClass. In the meanwhile, you can download the code and documentation here.