drupal_to_js

Versions
4.7 – 6
drupal_to_js($var)

Converts a PHP variable into its Javascript equivalent.

We use HTML-safe strings, i.e. with <, > and & escaped.

Related topics

▾ 6 functions call drupal_to_js()

drupal_call_js in includes/common.inc
Generates a Javascript call, while importing the arguments as is. PHP arrays are turned into JS objects to preserve keys. This means the array keys must conform to JS's member naming rules.
drupal_to_js in includes/common.inc
Converts a PHP variable into its Javascript equivalent.
taxonomy_autocomplete in modules/taxonomy.module
Helper function for autocompletion
update_do_update_page in ./update.php
Perform updates for the JS version and return progress.
upload_js in modules/upload.module
Menu-callback for JavaScript-based uploads.
user_autocomplete in modules/user.module
Retrieve a pipe delimited string of autocomplete suggestions for existing users

Code

includes/common.inc, line 1288

<?php
function drupal_to_js($var) {
  switch (gettype($var)) {
    case 'boolean':
      return $var ? 'true' : 'false'; // Lowercase necessary!
    case 'integer':
    case 'double':
      return $var;
    case 'resource':
    case 'string':
      return '"'. str_replace(array("\r", "\n", "<", ">", "&"),
                              array('\r', '\n', '\x3c', '\x3e', '\x26'),
                              addslashes($var)) .'"';
    case 'array':
      // Arrays in JSON can't be associative. If the array is empty or if it
      // has sequential whole number keys starting with 0, it's not associative
      // so we can go ahead and convert it as an array.
      if (empty($var) || array_keys($var) === range(0, sizeof($var) - 1)) {
        $output = array();
        foreach($var as $v) {
          $output[] = drupal_to_js($v);
        }
        return '[ '. implode(', ', $output) .' ]';
      }
      // Otherwise, fall through to convert the array as an object.
    case 'object':
      $output = array();
      foreach ($var as $k => $v) {
        $output[] = drupal_to_js(strval($k)) .': '. drupal_to_js($v);
      }
      return '{ '. implode(', ', $output) .' }';
    default:
      return 'null';
  }
}
?>
Login or register to post comments
 
 

All source code and documentation on this site is released under the terms of the GNU General Public License, version 2 and later. Drupal is a registered trademark of Dries Buytaert.