7

card.module

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

  currentRequest = $.ajax({
  timeout:0,
  cache: false,
  url: pageUrl,
  dataType: "json",
  type: "GET",
  success: function(data){
  $("#edit-field-currency-type-und-0-value").val(data.currency);

  }

});

ajax request module

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

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_encod($data);
}

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.

Thank You

12

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

drupal_json_output($data);

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.

1

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.

0

I've recently found this plug&play module that once enabled exposes APIs to list nodes and commends, to login/logout users and to create entities with REST calls that read and output JSON data:

https://www.drupal.org/project/rest_json

It doesn't require any further code or configuration.

  • WARNING: The module recommended in the above post is advertised as insecure and officially unsupported as of Wed 2017-01-25T13:38:03 – dreftymac Jan 25 '17 at 21:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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