Community Documentation

drupal_json

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.

▾ 8 functions call drupal_json()

book_form_update in modules/book/book.pages.inc
Renders a new parent page select element when the book selection changes.
poll_choice_js in modules/poll/poll.module
Menu callback for AHAH additions.
profile_admin_settings_autocomplete in modules/profile/profile.admin.inc
Retrieve a pipe delimited string of autocomplete suggestions for profile categories
profile_autocomplete in modules/profile/profile.pages.inc
Callback to allow autocomplete of profile text fields.
system_date_time_lookup in modules/system/system.admin.inc
Return the date for a given format string via Ajax.
taxonomy_autocomplete in modules/taxonomy/taxonomy.pages.inc
Helper function for autocompletion
user_autocomplete in modules/user/user.pages.inc
Menu callback; Retrieve a JSON object containing autocomplete suggestions for existing users.
_batch_do in includes/batch.inc
Do one pass of execution and inform back the browser about progression (used for JavaScript-mode only).

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);
  }
}
?>

Comments

Drupal 7

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, use drupal_set_header(). E.g.:

drupal_set_header('Content-Type: application/json');

Login or register to post comments