Sunday 22 January 2012

Converting PHP variables to Javascript variables

Here are some techniques for safely passing PHP variables to Javascript.

Ints and Floats
This one's pretty obvious.
var js_num = <?php echo $php_num; ?>;

Strings
Note that json_encode will take care of the Javascript string quoting delimiters.
var js_str = <?php echo json_encode($php_str); ?>;

Arrays and Associative Arrays
Arrays and associative arrays require that the type first gets encoded to JSON (the first call to json_encode) and then into a string (second call to json_encode) which can be parsed by a Javascript JSON parse function. JSON.parse is included in all recent browsers but to be sure of support use Douglas Crockford's json2.js file which will add it to any browser missing it. jQuery also provides a JSON parsing function.
var js_arr = JSON.parse(<?php echo json_encode(json_encode($php_arr)); ?>);
var js_obj = JSON.parse(<?php echo json_encode(json_encode($php_assoc)); ?>);

Objects
Objects are handled like associative arrays as if get_object_vars had been called upon the object first.

No comments:

Post a Comment