Drupal has a helpful AJAX API to run calls through AJAX, for example on links (use-ajax
class) or submit buttons (use-ajax-submit
class). Also AJAX can be used in the Drupal Form API to run AJAX calls for dynamic elements, submit or autocomplete for example.
Also content can very easy be loaded into Drupal Dialogs / Modals via AJAX!
But one thing that wasn't very well documented is, how to make such calls simply in custom Client JavaScropt code!
The call is simple (even if I think it could have been simpler):
const ajax = Drupal.ajax({
url: '/your-ajax-url?_wrapper_format=drupal_ajax',
});
ajax.execute();
I just added some example code to the Drupal Docs here: Trigger Ajax request with custom code (Client JavaScript) so hopefully in the future it will be easier to find, how to do that correctly.
Happy coding! ツ
Read more:
- https://www.drupal.org/docs/develop/drupal-apis/ajax-api/basic-concepts
- https://www.drupal.org/docs/develop/drupal-apis/ajax-api/core-ajax-callback-commands
Related: