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'
),
);
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'
),
);
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.
"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';
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.