Drupal Notes 4: enhance our module with jQuery AJAX/JSON

create quoteDisplay.js to contain:

var quoteDisplay = {}; // JS Namespace Object Creation
if(Drupal.jsEnabled){
$(document).ready(
function(){
$(“#quoteDisplay-origin”).after(“<a>Next &raquo;</a>”).next().click(quoteDisplay.randQuote);
}
);
/**
* A function to fetch quotes from the server,
* and display in the designated area.
*/

quoteDisplay.randQuote = function(){
$.get(Drupal.settings.quoteDisplay.json_url, function(data){
myQuote = Drupal.parseJson(data);
if(!myQuote.status || myQuotes.status == 0){
$(“#quoteDisplay-origin”).text(myQuote.quote.origin);
$(“#quoteDisplay-text”).text(myQuote.quote.text);
}
}); // End inline function
}
}

add this line to quoteDisplay.module file’s theme_quoteDisplay() function (after “drupal_add_js” line, before “$output = ‘

drupal_add_js($module_path . ‘/quoteDisplay.js’);
$opts = array(‘absolute’ => TRUE);
$json_url = url(‘quoteDisplay.json’, $opts);
drupal_add_js(
array(‘quoteDisplay’ =>
array(“json_url” => $json_url)), ‘setting‘);

also add these functions to our quoteDisplay.module file:

/*
* Callback to handle requests for
quoteDisplay content.
* @return
* JSON data.
*/

function quoteDisplay_item(){
$item = _quoteDisplay_get_quote();
drupal_set_header(‘Content-Type: text/plain; charset: utf-8’);
printf(
{ “quote”: { “origin”: “%s”, “text”: “%s” } }‘,
$item->title,
$item->body
);
}

/**
* Implementation of hook_menu()
* registers quoteDisplay.json
* will call quoteDisplay_item() when called
* anyone that may access content may access this path
* MENU_CALLBACK below is a bitmask,
* that doesn’t authomatically create links to this item in the menu or elsewhere,
* it simnply makes this accessible by URL,
* more than 20 such bitmask types may be used,
* see documentation.
*/

function quoteDisplay_menu(){
$items[‘quoteDisplay.json’] = array(
‘title’ => ‘Quote Display AJAX Gateway’,
‘page callback’ => ‘quoteDisplay_item’,
‘access arguments’ => array(‘access content’),
‘type’ => MENU_CALLBACK,
);
return $items;
}

now hit the url to see your JSON return! (you may need to clear your drupal cache of course)
http://localhost/yourDrupalSiteName/?q=quoteDisplay.json

Comments are closed.