Rebuild form AFTER ajax callback has run I have a form with a button that when pressed re-builds a different part of the form via an ajax request.

Upon clicking the button the form is rebuilt, then my ajax callback is called which saves the values from the form, and then returns part of the form.

The problem is the form is rebuilt BEFORE my callback which saves the values, and therefor alters how the form is built.

If I click the ajax button a second time then it works correctly as has the values from the previous ajax request when the form is build.

How can I get my callback function to run before the form is rebuilt?

function emtr_shift_plan_form($form, &amp;$form_state) {

    ddl('build'); // log that this function is being called

    $form['save'] = array(
        '#type' =&gt; 'button',
        '#submit' =&gt; array('emtr_shift_plan_form_ajax_submit'),
        '#value' =&gt; 'Save',
        '#ajax' =&gt; array(
            'callback' =&gt; 'emtr_shift_plan_form_ajax_submit',
            'wrapper' =&gt; 'postions',
        ),
        '#id' =&gt; 'ajax-save-form-values',
    );

    $form['postions'] = array(
        '#type' =&gt; ' container',
        '#prefix' =&gt; '&lt;div id="postions"&gt;',
        '#suffix' =&gt; '&lt;/div&gt;',
    );

    // code here to populate the positions container

}

function emtr_shift_plan_form_ajax_submit($form, &amp;$form_state) {

    ddl('ajax submit'); // log the ajax callback is being called

    $form_state['rebuild'] = TRUE; // As the form has already been rebuilt at this point what effect can this have?!?

    emtr_shift_plan_form_save($form, $form_state); // save the values

    // This is the point at which I want the form to be rebuilt

    return $form['positions'];

}


EDIT:

As a workaround I found it is possible to manually rebuild the form a second time in the ajax callback with $form = drupal_rebuild_form('emtr_shift_plan_form', $form_state);, but is seems inefficient building the form twice. Can I just swap the order of these events over as opposed to having the build the form twice per ajax request?
You could try like this making submit different and callback different and see if it helps.

$form['save'] = array(
    '#type' =&gt; 'button',
    '#submit' =&gt; array('emtr_shift_plan_form_ajax_submit'),
    '#value' =&gt; 'Save',
    '#ajax' =&gt; array(
        'callback' =&gt; 'emtr_shift_plan_form_ajax',
        'wrapper' =&gt; 'postions',
    ),
    '#id' =&gt; 'ajax-save-form-values',
);

function emtr_shift_plan_form_ajax($form, &amp;$form_state){
  return $form['positions'];
}
function emtr_shift_plan_form_ajax_submit($form, &amp;$form_state) {

    ddl('ajax submit'); // log the ajax callback is being called

    $form_state['rebuild'] = TRUE; // As the form has already been rebuilt at this point what effect can this have?!?

    emtr_shift_plan_form_save($form, $form_state); // save the values

    // This is the point at which I want the form to be rebuilt
}