Login

Drupal7 Ajax Response Handler

In our hook_form() implementation, we added ajax attributes to a couple of our form elements. The example below is our ajax response handler. In Drupal7 you can use a simple response handler which simply updates a single element (not shown here), or you can send a batch of client side commands. Our example below sends a batch of client side directives.

Normally, we would include a form validation and submit handler. Those handlers use methods like drupal_set_message() and form_set_error() to notify the user. Both drupal_set_message() and form_set_error() invoke full page repaints. Therefore, in the following example we move the notifications in to our ajax response. Thus the commands to change the look of our input field based upon whether the user entered a valid value. Note!

 function my_color_ajax_response($form, &$form_state) {
 
     $color_entered = trim($form_state['values']['color']);
     $allowed_values = array('red','white','blue');
     $message = '<div id="inner-message" class="';
     $commands = array();
 
    if (in_array($color_entered, $allowed_values)) {
        $myColor = new my_color();
        $myColor->setName(trim($form_state['values']['color']));
        $db= new dbMy_color();
        try {
            $dbResult = $db->add($myColor);
            $message.='information">Your vote for '.$myColor->getName().' Processed Successfully.</div>';
            $commands[] = ajax_command_css('#edit-color', array('background-color' => 'white'));
            $commands[] = ajax_command_css('#edit-color', array('border' => 'solid black 1px'));
            $commands[] = ajax_command_css('#message_area', array('class' => 'info'));
        } catch (Exception $e) {
            $message.='error">Error: An Unexpected Database Exception Occurred';
            $commands[] = ajax_command_css('#message_area', array('class' => 'error'),array('class' => 'error'));
        }
    } else {
        $message.='error">Error: You have entered an invalid color</div>';
        $commands[] = ajax_command_css('#edit-color', array('border' => 'solid red 1px'));
        $commands[] = ajax_command_css('#message_area', array('class' => 'error'),array('class' => 'error'));
    }
 
    $vars = _get_color_vote();
    $commands[]=ajax_command_html('#message_area',$message );
    $commands[] =ajax_command_html('#report_table', theme_table($vars));
 
    return array('#type' => 'ajax', '#commands' => $commands);
}