What is Ajax?
Ajax can update a webpage content by making asynchronous request without refreshing the current page. Using ajax we can perform various actions to fetch data from server and display at specific part of the html. In this article we will learn how to Ajaxify an anchor link using Drupal Ajax API without writing single line of JavaSciprt or jQuery.
In this example we will make a custom Controller class to render a link. Another method from same controller will be used to return data via Ajax Commands from Ajax API.
Step by step guide to Ajaxify an anchor link
Step 1: Register a path
# web/modules/custom/dcourse/dcourse.routing.yml
dcourse.example:
path: '/dcourse/my-first-page'
defaults:
_title: "Hello Custom module."
_controller: '\Drupal\dcourse\Controller\DcourseController::firstPage'
requirements:
_role: 'administrator'
Step 2: Make a controller to render the anchor link
# web/modules/custom/dcourse/src/Controller/DcourseController.php
<?php
namespace Drupal\dcourse\Controller;
class DcourseController {
public function firstPage() {
$build['content']['warapper'] = [
'#markup' => '<div id="ajaxLinkWrapper"></div>',
];
$build['content']['link'] = [
'#type' => 'link',
'#title' => 'Ajax Example link',
'#url' => Url::fromRoute('dcourse.ajax'),
'#attributes' => ['class' => ['use-ajax']],
'#attached' => [
'library' => [
'core/drupal.ajax'
],
],
];
return $build;
}
}
Step 3: Register another route to respond the ajax request
dcourse.ajax:
path: '/dcourse/ajax-example'
defaults:
_controller: '\Drupal\dcourse\Controller\DcourseController::ajaxDemo'
requirements:
_role: 'administrator'
Step 4: Implement a controller method the respond the ajax request.
public function ajaxDemo() {
$response = new AjaxResponse();
$response->addCommand(new HtmlCommand('#ajaxLinkWrapper', 'Hello from Ajax'));
return $response;
}
This method will replace the content of div element with id ajaxLinkWrapper. Complete Controller class will be like this.
# web/modules/custom/dcourse/src/Controller/DcourseController.php
<?php
namespace Drupal\dcourse\Controller;
class DcourseController {
public function firstPage() {
$build['content']['warapper'] = [
'#markup' => '<div id="ajaxLinkWrapper"></div>',
];
$build['content']['link'] = [
'#type' => 'link',
'#title' => 'Ajax Example link',
'#url' => Url::fromRoute('dcourse.ajax'),
'#attributes' => ['class' => ['use-ajax']],
'#attached' => [
'library' => [
'core/drupal.ajax'
],
],
];
return $build;
}
public function ajaxDemo() {
$response = new AjaxResponse();
$response->addCommand(new HtmlCommand('#ajaxLinkWrapper', 'Hello from Ajax'));
return $response;
}
}
Note: Make sure you have added `core/drupal.ajax` library to your render elements otherwise this link will not work.
'#attributes' => ['class' => ['use-ajax']]: This line is actually making this link as an Ajax link.
Conclusion
Working with Ajax can be complex but you can leverage the power of Drupal Ajax API and Ajax Command to do things without writing custom JS code.