How can I return actual JSON using Drupal? I'd like to implement a simple AJAX function locally that allows me to autocomplete node titles of already existing nodes as the user types. To that end, I need the ability to have an API that I can search on node titles. The problem is that when I output raw JSON, it comes surrounded by tags. So, no matter what I do, I keep getting...

&lt;html&gt;
    &lt;head&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;pre style="word-wrap: break-word; white-space: pre-wrap;"&gt; {json here}&lt;/pre&gt;
    &lt;/body&gt;
&lt;/html&gt;


I've tried implementing a custom page template that only outputs content already, that produced the same results. Here is how I am currently doing this, in my module file...

&lt;?php

/**
 * Implementation of hook_menu()
 */
function content_relation_menu() {
    $items = array();
    $items['api'] = array(
        'title' =&gt; 'Search',
        'page callback' =&gt; 'content_relation_get',
        'access callback' =&gt; TRUE,
        'type' =&gt; MENU_CALLBACK,
    );

    return $items;
}

function content_relation_get($term = '') {
    drupal_add_http_header('Content-Type', 'application/javascript; utf-8');
    $var = json_encode(
        db_query("SELECT nid,title FROM {node} WHERE title LIKE :title LIMIT 5", array(":title" =&gt; $term.'%'))-&gt;fetchAll()
    );
    echo $var;
    exit(0);
}


How can I return JUST raw JSON?
For Drupal 6, you can use drupal_json

function content_relation_get($term = '') {
    $result = db_query("SELECT nid,title FROM {node} WHERE title LIKE :title LIMIT 5", array(":title" =&gt; $term.'%'))-&gt;fetchAll()
    );
    drupal_json($result);
    exit;
}


For Drupal 7, change it to use drupal_json_output

function content_relation_get($term = '') {
    $result = db_query("SELECT nid,title FROM {node} WHERE title LIKE :title LIMIT 5", array(":title" =&gt; $term.'%'))-&gt;fetchAll()
    );
    drupal_json_output($result);
    drupal_exit();
}


It would also probably be safer to parse out the query to sanitize, error check, etc, instead of just trying to return the result.