Question

X post from http://drupal.org/node/953016

The Drupal 7 AJAX system is great, it works very smoothly for forms and even for links.

What I can't work out how to do in a sane way is to call it from javascript. I may want to have a dynamic page without a form and as part of that make a Drupal ajax call, specifically so that the ajax commands get run on return.

The most effective way I have found to do this so far is:

  dummy_link = $('<a href="'+uri+'" class="use-ajax">Loading Vars</a>');
  $(vars_div).append(dummy_link);
  Drupal.attachBehaviors(vars_div);
  dummy_link.click();

Which is effective but a huge hack. I havn't found a way to perform an ajax call and have the Drupal ajax framework do it, rather than the standard jquery framework.

I would have thought that it was possible to invoke the drupal ajax api directly, does anyone know how?

Was it helpful?

Solution

The short short answer is you'll want to get yourself to something like:

$.ajax(ajax.options);

Which is the jQuery part, but with a set of options that help you hook into the Drupal Goodness in terms of success handling, effects, etc. This is what is effectively what's hapening for you in your "huge hack" example.

Creating a new Drupal.ajax function programatically still requires a synthetic element:

base = 'someid'
element = $('<a href="'+uri+'" class="use-ajax">Loading Vars</a>');
element_settings = {'url': uri, 'event': 'click'}
myAjax = new Drupal.ajax(base, element, element_settings)

But you can at least trigger it without simulating a click in the UI:

myAjax.eventResponse(element, 'click')

It feels like there should be a better way to do this, but it requires another way to set up the initial ajax prototype that doesn't require a DOM element. Because so much of the interaction-set hinges on how to move data back into the DOM, I don't think this use-case is well-supported yet.

It may also be possible to go direct to jQuery with a proper set of options and get the effect you want, but the Drupal.ajax protoype functions self-refer quite a lot so doing it without a Drupal.ajax class seems dicey.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top