1 ajax_example_misc.inc ajax_example_render_link()

Demonstrates a clickable AJAX-enabled link using the 'use-ajax' class.

Because of the 'use-ajax' class applied here, the link submission is done without a page refresh.

When using the AJAX framework outside the context of a form or a renderable array of type 'link', you have to include ajax.js explicitly.

Return value

string: The HTML markup for the rendered link.

Related topics

File

modules/examples/ajax_example/ajax_example_misc.inc, line 21
AJAX Miscellaneous Topics.

Code

function ajax_example_render_link() {
  // backdrop_add_library is invoked automatically when a form element has the
  // '#ajax' property, but since we are not rendering a form here, we have to
  // do it ourselves.
  backdrop_add_library('system', 'backdrop.ajax');
  $explanation = t("
The link below has the <i>use-ajax</i> class applied to it, so if
JavaScript is enabled, ajax.js will try to submit it via an AJAX call instead
of a normal page load. The URL also contains the '/nojs/' magic string, which
is stripped if JavaScript is enabled, allowing the server code to tell by the
URL whether JavaScript was enabled or not, letting it do different things based on that.");
  $output = "<div>" . $explanation . "</div>";
  // The use-ajax class is special; that the link will call without causing a
  // page reload. Note the /nojs portion of the path; when JavaScript is
  // enabled, this part will be stripped from the path before it is called.
  $link = l(t('Click here'), 'ajax_link_callback/nojs/', array('attributes' => array('class' => array('use-ajax'))));
  $output .= "<div id='myDiv'></div><div>$link</div>";
  return $output;
}