AHAH Simplest Example: #ahah on the submit button, replace a region

Note that this is currently maintained in the Examples project so the code here may not be the latest.

The essence of AHAH is that you mark an element of a form as the one that activates AHAH behavior, and you tell it what section of the HTML is to be replaced when it's activated.

The form we're using here has a "markup" element, which is just plain HTML. It has a prefix and suffix that mention its CSS ID. The CSS ID will be used by the javascript running in the background to determine what's to be replaced.

The submit is marked as an element with AHAH behavior with the "#ahah" marker. It's given a Drupal path for the callback. You can actually point your web browser at this path and see what happens as a debugging procedure. Here you can hit the callback in your browser (http://d6.drupalexamples.info/examples/ahah_example/simplest_ahah/callback).

When the submit button is pressed, instead of doing the traditional HTTP submit of the page, javascript provided by Drupal calls the callback, gets the resulting HTML (as a JSON object), and then replaces the section of the code (The div with ID "box") with the HTML replacement.

(This one is at http://d6.drupalexamples.info/examples/ahah_example/simplest_ahah.)

Here's an example of the very simplest AHAH behavior.

<?php
/**
 * @file
 * A Hello-world AHAH. Just swaps out a markup section on submit
 */
function ahah_demo_simplest() {

 
$initial_markup = '<div style="background: lightblue; width: 150px; height: 150px">' . t('This is a blue box') . '</div>';

 
$form['box'] = array(
   
'#type' => 'markup',
   
'#prefix' => '<div id="box">',
   
'#suffix' => '</div>',
   
'#value' => $initial_markup,
  );

 
$form['submit'] = array(
   
'#type' => 'submit',
   
'#ahah' => array(
     
'path' => 'ahah_demo/simplest_ahah/callback',
     
'wrapper' => 'box',
    ),
   
'#value' => t('Click Me'),
  );

  return
$form;
}


function
ahah_demo_simplest_callback() {
 
$colors = array('red','orange','blue','green','black');
 
$color = $colors[array_rand($colors)];
 
$output = '<div id="box" style="background-color:' . $color .
   
'; width: 150px; height: 150px;">This is ' . $color . ' box</div>';
  print
drupal_json(array('status' => TRUE, 'data' => $output));
  exit();
}
?>
Topics: 
Drupal theme by Kiwi Themes.