I am trying to understand and get the example working that was discussed here http://api.drupal.org/api/drupal/includes--ajax.inc/group/ajax

I understand the form building function.

function ajax_example_simplest($form, &$form_state) {
    $form = array();
    $form['changethis'] = array(
    '#type' => 'select',
    '#options' => array(
      'one' => 'one',
      'two' => 'two',
      'three' => 'three',
    '#ajax' => array(
      'callback' => 'ajax_example_simplest_callback',
      'wrapper' => 'replace_textfield_div',

    // This entire form element will be replaced with an updated value.
    $form['replace_textfield'] = array(
    '#type' => 'textfield',
    '#title' => t("The default value will be changed"),
    '#description' => t("Say something about why you chose") . "'" .
    ? $form_state['values']['changethis'] : t("Not changed yet")) . "'",
    '#prefix' => '<div id="replace_textfield_div">',
    '#suffix' => '</div>',
    return $form;

What I don't understand is what is happening in ajax callback function.

function ajax_example_simplest_callback($form, $form_state) {
    // The form has already been submitted and updated. We can return the replaced
    // item as it is.
    return $form['replace_textfield'];

The same form field is returned. I thought we can change the value or something for the form item $form['replace_textfield'] through ajax callback function. Can some one pls help me to explain this part?

2 Answers 2


All ajax logic placed in construct form function (ajax_example_simplest), ajax callback just return part of form (replace_textfield) or ajax commands. Its Drupal architecture. This form can be validate and altering.

  • Thanks for the reply. That cleared a part of it. If i have to change button text on ajax callback when clicked on, what should i be returning from ajax callback function? Commented Sep 28, 2011 at 2:01
  • $commands[] = ajax_command_invoke('#edit-submit', 'val', array('New button text')); return array('#type' => 'ajax', '#commands' => $commands);
    – xandeadx
    Commented Sep 28, 2011 at 11:49

Please spend some time with the AJAX Example in the Examples project. This is also available on api.drupal.org, but it's best just to get the code and experiment with it. It tries to explain exactly what's going on and best practices with it. Also, http://randyfay.com/ajax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.