15
votes

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?

2

2 Answers

37
votes

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

21
votes

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:

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