Drupal – Call Javascript after form submission

Again, i will use the custom module i have created in
Drupal – Introduction to Drupal Theming @ 3

This time we add a custom form called ykyuen_greeting_form in the preprocess function.

ykyuen.module

...
/**
 * Implementation of theme_eureka().
 */
function ykyuen_preprocess_eureka($variables) {  
  $variables['extra'] = variable_get('eureka_greeting', 'Hello World!');
  $variables['my_form'] = drupal_get_form('ykyuen_greeting_form');
  if (isset($_SESSION['greeting'])) {
    // Call the javascript if $_SESSION['greeting'] is set
    $greeting = $_SESSION['greeting'];
    drupal_add_js("Drupal.behaviors.ykyuen = function() { alert('$greeting'); }", 'inline');
    unset($_SESSION['greeting']);
  }
}

/**
 * Custom form
 */
function ykyuen_greeting_form($form_state) {
  $form['greeting'] = array(
    '#type' => 'textfield',
    '#title' => t('Enter the greeting message'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit'
  );
  
  if(isset($form_state['storage'])) {
    $_SESSION['greeting'] = $form_state['storage']['alert_msg'];
  }
  return $form;
}

/**
 * Custom form submission callback
 */
function ykyuen_greeting_form_submit($form, &$form_state) {
  // Set the $form_state['storage'] whenever the form is submitted
  $form_state['storage']['alert_msg'] = 'Hello World';
}

 

And we also need to print the form in the eureka.tpl.php.

<h2>Theme .tpl.php example</h2>
<p><a href="<?php print $link; ?>"><?php print $name; ?></a></p>
<p><?php print $extra; ?></p>
<?php print $my_form; ?>

 

Done =)

Reference: Drupal Forum – Forms API, in submit function, call javascript function and store variables in Drupal.settings

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.