Invoke Drupal #ajax element via JavaScript / jQuery

You can easily invoke a Drupal 7 form element's #ajax callback via JavaScript, you just have to know how to trigger the binding properly. If you look at the inline JavaScript that Drupal prints on your form's page, you'll see local Drupal settings as well as ajax settings to be used on the current page. Here's an example:

jQuery.extend(...Drupal's JavaScript settings..."ajax":{"edit-field-my-field-name-und-0-add-item":{"callback":"example_field_widget_form_ajax","wrapper":"example-field-widget-form-wrapper","method":"replaceWith","effect":"fade","event":"mousedown","keypress":true,"prevent":"click","url":"\/example.com\/drupal\/system\/ajax","submit":{"_triggering_element_name":"op","_triggering_element_value":"Refresh"}}},"states":{"#edit-revision":{"checked":{"textarea[name=\u0022log\u0022]":{"empty":false}}}},"anonymous":"Anonymous"});

You can see that the element with the ID "edit-field-my-field-name-und-0-add-item" requires the event "mousedown" (but not "click"!) to trigger the #ajax callback. I had tried $.click(), $.submit(), etc., and couldn't figure out why the button element wouldn't run the callback until I saw that the event for buttons is "mousedown". So, jQuery('#my-item').trigger('mousedown'); does the trick.

Comments

Matt's picture

Just saved me a lot of time searching. Tried click and submit as well but ajax was not triggered. Mousedown worked perfectly. Thanks.

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.