1

I am using Drupal 7. I want to rebuild a part of form when a button is clicked. My form looks like this:

$form['me'] = array(
    '#type' => 'fieldset',
    '#value' => t('name'),
    '#prefix' => '<div id="me-wrapper>',
    '#suffix' => '</div>'
);

It contains various text fields and a submit button. The submit button looks like

$form['me']['save'] = array(
    '#type' => 'submit',
    '#validate' => array('save_validate'),
    '#submit' => array('save_submit'),
    '#ajax' => array(
        'wrapper' => 'me-wrapper',
        'callback' => 'me_ajax_callback'
    ),
);

in the save_submit function I set $form_state['rebuild] = true;

in ajax callback function

function me_ajax_callback($form, $form_state) {
    return $form['me'];
}

Now, what happens is first time when I click submit, the ajax returns data and replaces the wrapper. But, 2nd time when I do so, I get a POST Internal Server Error 500.

Looking around the Form API, I set $form_state['no_cache']=true; in submit handler and that prevents the POST error but still the AJAX response is empty.

It works fine if, I reload the page. So, in short, the first time I hit submit I get an AJAX response. On the second time, the response is blank.

2
  • What do your server logs say? An Internal Server Error 500 could mean anything. Commented Aug 9, 2017 at 17:52
  • have you tried returning some text in the call back function? the value you should return have to be accessed via $form_state['values'] rather than the $form['me']? because you won't get what you need with $form, you have to use $form_state['values']['me'] why ? : because when you submit the '$form_state` holds your post values.
    – danuddara
    Commented Aug 9, 2017 at 21:27

1 Answer 1

2

Ok, I have solved the issue and this might help someone in future. I was dealing with a form which was actually a collection of various small forms. Each small form had various text fields and submit handler. So, when reloading a small form using AJAX I was setting $form_state['rebuild'] = true, this in process rebuilt the whole form in the back. But AJAX callback only rendered a small part of form into the wrapper. So, when I pressed the button again there was post error as Drupal was expecting values in new rendered form whereas it got a mixture of Old and new form. It happens because Drupal while rendering a form into HTML adds id to it, e.g., id = edit-save but when we rebuild it without reloading the page, it changes to something like id = edit-save--2 and which keeps on to increment every time it's rebuilt. So, if your form needs rebuilding, reload the whole form else set $form_state['rebuild'] = false and that should allow subsequent AJAX calls without any post error.

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.