My original post caused some confusion, so I'm re-writing it for clarity.
In Drupal, if you have an #ajax callback in a form, you can do something like this:
function my_ajax_callback(array &$form, FormStateInterface $form_state)
{
$response = new AjaxResponse();
$response->addCommand(new AlertCommand(t('This is from an ajax callback'));
return $response;
}
This in turn triggers Drupal.ajaxCommands.prototype.alert(), which is located in ajax.js.
Alternatively, I can create an ajax callback of my own, that has nothing to do with a form. example.routing.yml:
mymodule.ajax
path: '/mymodule/ajax'
defaults:
_controller: 'Drupal\my_module\Controller::ajaxCallback'
# (remainder not shown)
I can create an AjaxResponse in this callback:
class Controller extends ControllerBase
{
public function ajaxCallback()
{
$response = new AjaxResponse();
$response->addCommand(new AlertCommand(t('This is from an ajax callback'));
return $response;
}
}
In this case, debugging has shown me that the AjaxResponse returns my command to the browser, but Drupal.ajaxCommands.prototype.alert() is not triggered.
Further debugging has shown me that ajax commands are only triggered if the AjaxResponse comes from an #ajax callback in a form, not if it's from a non-form ajax callback.
So my question is, does anyone know how to invoke ajax commands when the commands are returned from non-form ajax callback?