9

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?

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I have the same basic challenge in Druapl 6 with CTools, and having one good pattern for both would be great.
Thanks Josh, I looked at doing it without the drupal.ajax class, but came to the same conclusion you did. I am happy with your answer, I was worried I was missing something obvious but don't think I was now.
I'll keep this on my radar though. I think a better technique can emerge and we can have a general "best practice" for others. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.