3

How do I add some JavaScript functions before Ajax begins, with FAPI?

$form['submit'] = array(    
  '#type' => 'submit',
  '#value' => 'Upload',
  '#ajax' => array(
    'callback' => 'ajax_submit_key_dump'
  ),
);
  • Hello user871, and welcome on Drupal Answers. What do you mean by "adding some JavaScript functions"? What are you trying to achieve? – kiamlaluno Apr 5 '11 at 12:38
  • I whant to hide some divs. $('.mydiv').hide(); – user871 Apr 5 '11 at 16:15
0

You can add a javascript file to a form using the #after_build property:

$form['#after_build'] = array('my_js_add_function');

....

function my_js_add_function($form, &$form_state) {
  drupal_add_js(...);
  return $form;
}

Using #after_build instead of adding the js in the form definition makes sure that the JS is added even if the form is gotten from cache.

In the JavaScript file you can add whatever jQuery you want to, a click handler on the submit button should do what you want.

| improve this answer | |
  • 2
    Attaching the JS is one thing, but getting it to run onclick of an object that Drupal's ajax.js has already "hijacked" doesn't seem to register. – Charlie Schliesser Jan 30 '12 at 20:59
6

"beforeSubmit" handler attached that way will be executed right before Ajax request:

(function ($) {
  Drupal.behaviors.ReplaceWithAnyTextYouWant = {
    attach: function (context, settings) {
      // 'edit-submit' is the element ID where you execute the #ajax.
      Drupal.ajax['edit-submit'].options.beforeSubmit = function(form_values, element_settings, options) {
      // If cancel is clicked, do not continue submitting.
      if (!confirm('Are you sure you want to continue?')) {
          return false;
      }
    }
  };
})(jQuery);

You could perform some pre-submit validation of the user input, and even cancel form submission by returning false

Here is a good example

'edit-submit' - is the element html ID of submit button with '#ajax' settings. 'edit-' prefix is attached to the key of your form array item containing triggering element (submit button in your case). For $form['my-submit'] = array(...), html ID of the resulting button will: "edit-my-submit".

JS file with code shown above, could be attached to your form in form constructor:

$form['#attached']['js'][] = drupal_get_path('module', 'your_module') . '/js/file.js';
| improve this answer | |
0

I have created a custom module; using hook_form_alter() I have added a JavaScript file to one of my content type forms. If you need more details, say it.

| improve this answer | |
  • Hello @user709, I have a form, that post file to the server throw ajax, and i need execute some jquery comands like $('.mydiv').hide(); befor ajax began send file to server. – user871 Apr 7 '11 at 8:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.