| 6 common.inc | drupal_json($var = NULL) |
Return data in JSON format.
This function should be used for JavaScript callback functions returning data in JSON format. It sets the header for JavaScript output.
Parameters
$var: (optional) If set, the variable will be converted to JSON and output.
File
- includes/
common.inc, line 2573 - Common functions that many Drupal modules will need to reference.
Code
<?php
function drupal_json($var = NULL) {
// We are returning JavaScript, so tell the browser.
drupal_set_header('Content-Type: text/javascript; charset=utf-8');
if (isset($var)) {
echo drupal_to_js($var);
}
}
?> Login or register to post comments
Comments
Drupal 7
The equivalent function in Drupal 7 is http://api.drupal.org/api/function/drupal_json_output/7
See http://drupal.org/update/modules/6/7#rename-drupal-to-js for more information.
No need to print result.
Overlooked by me. The print
<?php print drupal_json($data) ?>is not necessary.
Using jquery's ajax functions
Using jquery's ajax functions you can have problems with IE7 and "expected semicolon" errors, because of the header is not correctly interpreted.
It's too late to fix it in D6, so make your own function, using
drupal_add_http_header('Content-Type', 'application/json');,That's the correct header, and Drupal 7 is using it also.
D6: drupal_set_header()
drupal_add_http_header()is a D7 function. To roll your own JSON response function in D6, usedrupal_set_header(). E.g.:drupal_set_header('Content-Type: application/json');