18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

JavaScript in <strong>Drupal</strong><br />

The page callback where the link lives, starts by using drupal_add_js() to add<br />

misc/ajax.js. This JavaScript does the work to automatically make the AJAX<br />

work. This is followed by a link with a callback to hello_world_link_callback/<br />

nojs/. The first part of this link is the callback where the AJAX request is handled.<br />

The /nojs/ at the end is special. When JavaScript is not available it is passed to the<br />

response function so it knows it was called to be a full page load. When JavaScript<br />

is available it is replaced with /ajax/. This is passed into the callback function so it<br />

knows it was called via an AJAX request.<br />

What makes this link become an AJAX link is the class being added with the name<br />

use-ajax. The JavaScript file we added at the beginning, ajax.js, looks for links<br />

with this class and converts them into AJAX.<br />

function hello_world_link_response($type = 'ajax') {<br />

if ($type == 'ajax') {<br />

$output = t("Hello World!");<br />

$commands = array();<br />

$commands[] = ajax_command_append('#saying-hello', $output);<br />

$page = array('#type' => 'ajax_commands', '#ajax_commands' =><br />

$commands);<br />

ajax_deliver($page);<br />

}<br />

else {<br />

return t("Hello World in a new page.");<br />

}<br />

}<br />

When the callback to handle the request is called, the type of action is passed in.<br />

When no JavaScript is available, nojs is passed in. When the request is AJAX, ajax<br />

is passed in. This can be used in the callback functions logic to properly respond<br />

to each case.<br />

In this case we use an if statement. When the request is AJAX, we respond in one<br />

way and when JavaScript is not available we respond differently.<br />

When the request is an AJAX callback we start by creating the response text of "Hello<br />

World!". This is followed by creating an array to hold commands we want <strong>Drupal</strong><br />

to execute and adding a command to it.<br />

A command is an action we want the JavaScript to perform when it receives the<br />

AJAX response. The commands provide ways in which jQuery can manipulate the<br />

content of the page with the responded data. In this case the command used is the<br />

ajax_command_append(). This command accepts a jQuery selector and content.<br />

The content is appended to the selector. This <strong>Drupal</strong> function utilizes the<br />

jQuery.append() function.<br />

[ 308 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!