2

I'm using Drupal 7 field API to reload part of my form through AJAX. I have a button which makes the call but I would like to remove it and make the call programmatically as a response to a specific event. Here is my code for the AJAX button:

$form['documents']['reload_document_list_button'] = array(
  '#type' => 'button',
  '#value' => 'Обновить список документов',
  '#ajax' => array(
    'callback' => 'reload_document_list',
    'wrapper' => 'document-list',
    'method' => 'replace',
  ),
);

(See http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#ajax for details.) Is there a way to do this?

P.S. I know I can style the button to make it invisible and trigger 'click' event, but I am looking for a neater way to do this.

bandolero
  • 131
  • 1
  • 7

1 Answers1

6

There are two ways you can do this, I think:

First, the #ajax property as you might have read accepts an event key. For the button element by default, this event is mousedown. (You can check it here) You can change it to a custom event, say customEvent and trigger this custom event from your Javascript code as jQuery('#button-id').trigger('customEvent');.

Alternatively, you can chuck the #ajax property itself. Set up an AJAX endpoint (using hook_menu) and set reload_document_list as its callback. Add custom Javascript to make the request and handle the response. You can take a look at the way Drupal sends the AJAX request when you use #ajax from misc/ajax.js and use that as a reference if you want.

  • Amar, thanks for your reply! For now I decided to use the first advice, but instead of creating a custom event I just trigger the `mousedown` event. As for the second advice, yes, it is possible and I know how to do it, but I want to keep as close as possible to the Drupal Form API framework, including its Javascript part, which, unfortunately, isn't documented at all. This is why I prefer the first solution. – bandolero Jun 25 '12 at 00:10
  • 1
    This solved a problem I was having, so thanks! I was trying to trigger an Ajax call by triggering the click event on a button, but nothing was happening. Changing it to the mousedown worked a treat. – James Shields Nov 05 '12 at 13:00