Please enable JS

Trigger Drupal Custom AJAX Programmatically

Drupal AJAX call that can be triggered programmatically from Javascript.
June 22/Brian Young/Drupal 7Software

I needed to trigger some Drupal server side code via an AJAX event from some client-side logic. Everything I found online required the event to be bound to an element, so I'd have to hide the element and programmatically trigger something like $('.dummy-element').click()

Solution

I ended up binding a custom Drupal AJAX event to the body element. See Below

  1. // Your custom Javascript file:
  2. (function ($) {
  3. $(function () {
  4. /**
  5.   * Add an extra function to the Drupal ajax object that is specific to our
  6.   * custom Drupal menu callback for: "custom/ajax/%/%".
  7.   */
  8. Drupal.ajax.prototype.customAjaxHandler = function (arg1, arg2) {
  9. // Do not perform another ajax command if one is already in progress.
  10. if (this.ajaxing) {
  11. return false;
  12. }
  13.  
  14. // Need to add the two url arguments.
  15. this.options.url = this.options.url.replace('%/%', (arg1 + '/' + arg2));
  16.  
  17. try {
  18. $.ajax(this.options);
  19. }
  20. catch (err) {
  21. console.log('An error occurred while attempting to process ' + this.options.url);
  22. return false;
  23. }
  24. };
  25.  
  26. });
  27.  
  28. })(jQuery);
  1. // In your_module.module
  2. /**
  3.  * Implements hook_menu().
  4.  */
  5. function your_module_menu() {
  6. return array(
  7. 'custom/ajax/%/%' => array(
  8. 'page callback' => 'custom_module_update_callback',
  9. 'page arguments' => array(2, 3),
  10. 'access callback' => true,
  11. 'delivery callback' => 'ajax_deliver', /* <----Important part */
  12. 'theme callback' => 'ajax_base_page_theme', /* <--- Important part */
  13. 'type' => MENU_CALLBACK,
  14. ),
  15. );
  16. }
  17.  
  18. function custom_module_callback($arg1, $arg2) {
  19. return array(
  20. '#type' => 'ajax',
  21. '#commands' => array(
  22. ajax_command_replace('#element-wrapper-id-' . $arg1, "<div id=\"#element-wrapper-id-" . $arg1 . "\">some custom markup to return to the page.</div>")
  23. )
  24. );
  25. }

Example Javascript Usage

You can now trigger an AJAX event via JS by calling our custom Drupal AJAX handler by instantiating an event bound to the `body` element:

  1. new Drupal.ajax(null, jQuery(document.body), {url: '/pane_ajax/update/%/%'})
  2. .customAjaxHandler('arg-val1', 'arg-val2');


RELATED POSTS


Comments/ 0


LEAVE A COMMENT

(If you're a human, don't change the following field)
Your first name.
(If you're a human, don't change the following field)
Your first name.
(If you're a human, don't change the following field)
Your first name.
But why?

My random thoughts and documentation on the various hardware and software projects that occupy my day-to-day. My only hope is that other people can benefit from my notes.

Recent posts
Categories