Skip to content

Instantly share code, notes, and snippets.

@cravecode
Last active June 21, 2016 18:51
Show Gist options
  • Save cravecode/2f8c07afea80d8ade4c0dd8e93052b8a to your computer and use it in GitHub Desktop.
Save cravecode/2f8c07afea80d8ade4c0dd8e93052b8a to your computer and use it in GitHub Desktop.
Using jQuery with custom Drupal page callback that returns Drupal AJAX command.

JS:

// Add a custom
(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);

your_module.module

/**
 * Implements hook_menu().
 */
function your_module_menu() {
  return array(
    'custom/ajax/%/%' => array(
      'page callback' => 'custom_module_update_callback',
      'page arguments' => array(2, 3),
      '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) {
  return array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace('#element-wrapper-id-' . $arg1, "<div id=\"#element-wrapper-id-" . $arg1 . "\">some custom markup to return to the page.</div>")
    )
  );
}

Usage example:

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');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment