I'm trying to figure out AJAX in Drupal 8.
I have a custom module that works, using AJAX to change the content of a div when a link is clicked.
The API says:
Many different events can trigger Ajax responses, including:
Clicking a button Pressing a key Moving the mouse
How do I trigger the same process that Drupal's AJAX does when a function is called from a JavaScript object's event firing instead?
JavaScript Object
function calledOnSomeEvent(e) {
String data = e.target.data;
// do something to call AJAX with the data
}
The AJAX backend works with this route:
myModule.routing.yml
myModule.myRoute:
path: '/nojs/myFunction/{myParameter}'
defaults:
_controller: '\Drupal\myModule\MyController::myFunctionCallback'
_title: 'myFunction'
requirements:
_permission: 'access content'
HTML
<a href="nojs/myFunction/testData" class="use-ajax">Click for testData!</a>
My understanding is that Drupal injects some sort of event when that link is clicked, or the URL is just changed, and the controller is only activated when that URL is changed.
JavaScript
(function($, Drupal) {
Drupal.AjaxCommands.prototype.myFunction = function(ajax, response, status){
$('#targetDiv').html(response.data);
}
})(jQuery, Drupal);
I omitted PHP code for the controller, which creates a command. The command renders the output to Drupal.AjaxCommands.prototype.myFunction, which updates the div.
Is an XMLHttpRequest the only way to make JavaScript interact with the route/PHP? If so, what path should be used?
I think there might be a way for JavaScript interact with Drupal's AJAX handler to call the same function that clicking the link changed with "use-ajax" does, since that's being handled in some way...
Any insight would be appreciated.
Thanks!