How to Trigger Existing, Non-Form Ajax from JavaScript Event
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!
Answers 1
If you don't want to ajaxify a link by adding the class
use-ajax
you can trigger an Ajax request programmatically:This creates an Ajax object with the endpoint as url and executes it. The endpoint has to be a controller returning an AjaxResponse.
You find more options in the comments of
Drupal.ajax
in ajax.js:Your second question, is an XMLHttpRequest the only way to make JavaScript interact with the route/PHP? If so, what path should be used?
You can use a normal non drupal
$.ajax()
, then you have no restrictions for the format. The controller can return JSON (which Drupal uses for it's own ajax) or any other format. It's then your job to process the returned data in javascript.