1

I ran into this issue on my own plugin and then decided to download the Drupal Example Modules to discover the same issue was happening to me in the 'ajax_example' section.

Ajax calls don't seem to queue, and the last message sent to the server overrides the last.

This is the code I am using. (It can also be found in ajax_example.module.)

function ajax_example_autotextfields($form, &$form_state) {
  $form['ask_first_name'] = array(
    '#type' => 'checkbox',
    '#title' => t('Ask me my first name'),
    '#ajax' => array(
      'callback' => 'ajax_example_autotextfields_callback',
      'wrapper' => 'textfields',
      'effect' => 'fade',
    ),
  );
  $form['ask_last_name'] = array(
    '#type' => 'checkbox',
    '#title' => t('Ask me my last name'),
    '#ajax' => array(
      'callback' => 'ajax_example_autotextfields_callback',
      'wrapper' => 'textfields',
      'effect' => 'fade',
    ),
  );
  $form['textfields'] = array(
    '#title' => t("Generated text fields for first and last name"),
    '#prefix' => '<div id="textfields">',
    '#suffix' => '</div>',
    '#type' => 'fieldset',
    '#description' => t('This is where we put automatically generated textfields'),
  );

  // Since checkboxes return TRUE or FALSE, we have to check that
  // $form_state has been filled as well as what it contains.
  if (!empty($form_state['values']['ask_first_name']) && $form_state['values']['ask_first_name']) {
    $form['textfields']['first_name'] = array(
      '#type' => 'textfield',
      '#title' => t('First Name'),
    );
  }
  if (!empty($form_state['values']['ask_last_name']) && $form_state['values']['ask_last_name']) {
    $form['textfields']['last_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Last Name'),
    );
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Click Me'),
  );

  return $form;
}

function ajax_example_autotextfields_callback($form, $form_state) {
  return $form['textfields'];
}

This is the screenshot of the page.

Generate Textfield

After selecting 'first name', 'second name' before 'first name' has time to finish loading.

Generate Textfield with missing fields

The 'first name' field is never loaded.

How can I fix this?

0

Drupal doesn't queue AJAX requests, no. If it's causing a problem, you might want to implement some JS to disable the form while a request takes place.

Alternatively, as it doesn't appear your fields are required, you could use #states instead. They don't require an AJAX call, but (depending on your ultimate requirements of course) will give you the same effect as your current code.

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.