Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal create a page that outputs JSON

Tags:

json

drupal

I would like to ask can one create a page that outputs JSON data as a response to Jquery Ajax request?

In a non-drupal way, I would just create a php file, for example mypage.php and then I would use http://example.com/mypage.php?foo=bar as the URL for my AJAX request. This page will then output JSON data using json_encode().

How can I do it the Drupal way?

like image 328
r2b2 Avatar asked Sep 03 '10 13:09

r2b2


2 Answers

A working example of scott reynen's hint: in drupal 7, in a module called mymodule, write

function mymodule_menu() {
    $items['fancystuff/json'] = array(
        'access callback'   => true, // available to all
        'page callback'     => 'mymodule_fancystuff_object', // defined below
        'delivery callback' => 'drupal_json_output' 
    );
    return $items;
}



function mymodule_fancystuff_object() {
    return array('test'=>true,'dummy'=>array(0,1));
}

clear your caches, goto http://example.com/fancystuff/json and behold

like image 200
commonpike Avatar answered Nov 06 '22 21:11

commonpike


The JSON server module gives you JSON output of nodes.

If you want more custom JSON, you can use hook_menu() to create a new menu callback (basically a URL path pointed to a function) and then use:

  • drupal_json() - Drupal6
  • drupal_json_output() - Drupal7

within that callback to send the output as JSON rather than the default HTML.

like image 21
Scott Reynen Avatar answered Nov 06 '22 21:11

Scott Reynen