Is this the correct way to return json data. If not, how should it be accomplished? I would like to return the data back to car.module.


drupal_add_js('jQuery(document).ready(function () {

  currentRequest = $.ajax({
  cache: false,
  url: pageUrl,
  dataType: "json",
  type: "GET",
  success: function(data) {


AJAX request module

$items['mccurr/%'] = array(
  'title' => '', 
  'page callback' => 'ajax_currency_type', 
  'access arguments' => array('access content'), 
  'page arguments' => array(1),

function ajax_currency_type($ccode) {
 drupal_add_http_header('Content-Type', 'application/javascript; utf-8');
  $query = "SELECT countries_country.currency 
    FROM countries_country
    WHERE countries_country.iso2 = '".$ccode."'";

  $data = db_query($query);

  return drupal_json_encode($data);

3 Answers 3


To return $data in json format using Drupal-7's page callback output, you should return through :


in your page callback function. For more ref : http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_json_output/7

Note : in your javascript in car.module, var pageUrl seems undefined. Make sure it is defined.


You really should never pass unsanitized input anywhere, see "Bobby Tables".

Drupal has the facility to escape database parameters like this;

$query = "SELECT countries_country.currency 
    FROM countries_country
    WHERE countries_country.iso2 = :ccode";

$data = db_query($query, array(':ccode' => $ccode));

Note that you'll also need to ->fetchAll() else you're just returning a database object.


I've recently found the REST/JSON module that once enabled exposes APIs to list nodes and commends, to log in / log out users, and to create entities with REST calls that read and output JSON data.

It doesn't require any further code or configuration.

This module is unsupported due to a security issue the maintainer didn't fix, since June 8, 2016.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.