I created a simple form. How could I add JavaScript commands after form was validated? Why is it so hard do this?

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'submit',
  '#validate' => 'my_validate_callback',
  '#ajax' => array(
    'callback' => 'my_form_callback',
    'method' => 'replace',
    'wrapper' => 'form-wrap',
    'effect' => 'fade'
  • Could you be more descriptive of the problem. Why add js only after form is validated. What are you trying to do? – Hardik Rawal Aug 1 '15 at 18:52
  • hello, i'm trying run a fancybox command when validate return some error, for open a div that it's a popup. – davide Aug 2 '15 at 19:52

If you only want to add a JS file in validate or Ajax handler function you just need to add JS to form with drupal_add_js or attach it to form.

This is an example of how can you add JavaScript in Ajax callback function:

function my_form_callback(&$form,$form_state){
if(some validation ){
$form['#attached']['js'] = array(
  drupal_get_path('module', 'ajax_example') . '/ajax_example.js',
return $form;
| improve this answer | |
  • I want execute a javascript when validate callback return some errors and when all it's okay. if i use $form['#prefix'] = '<script>...</script'; ??? – davide Aug 2 '15 at 19:58

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.