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()
I ended up binding a custom Drupal AJAX event to the body element. See Below
// Your custom Javascript file: (function ($) { $(function () { /** * Add an extra function to the Drupal ajax object that is specific to our * custom Drupal menu callback for: "custom/ajax/%/%". */ Drupal.ajax.prototype.customAjaxHandler = function (arg1, arg2) { // Do not perform another ajax command if one is already in progress. if (this.ajaxing) { return false; } // Need to add the two url arguments. this.options.url = this.options.url.replace('%/%', (arg1 + '/' + arg2)); try { $.ajax(this.options); } catch (err) { console.log('An error occurred while attempting to process ' + this.options.url); return false; } }; }); })(jQuery);
// In your_module.module /** * Implements hook_menu(). */ function your_module_menu() { 'page callback' => 'custom_module_update_callback', 'access callback' => true, 'delivery callback' => 'ajax_deliver', /* <----Important part */ 'theme callback' => 'ajax_base_page_theme', /* <--- Important part */ 'type' => MENU_CALLBACK, ), ); } function custom_module_callback($arg1, $arg2) { '#type' => 'ajax', ajax_command_replace('#element-wrapper-id-' . $arg1, "<div id=\"#element-wrapper-id-" . $arg1 . "\">some custom markup to return to the page.</div>") ) ); }
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:
new Drupal.ajax(null, jQuery(document.body), {url: '/pane_ajax/update/%/%'}) .customAjaxHandler('arg-val1', 'arg-val2');
Software engineer by profession, embedded systems tinkerer, husband, father, fantasy novel devourer, wine lush, beer and cheese connoisseur