Rebuild form is not working in #ajax callback I've tried to build a form with #ajax submit function and rebuild the form. The following is my code.

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

 if(!isset($form_state['num_names'])){
   $form_state['num_names']=2;
 }

 // Create wrapper for ajax
 $form['#prefix'] = '&lt;div id="form-wrapper"&gt;';
 $form['#suffix'] = '&lt;/div&gt;';

 for ($i = 1; $i &lt;= $form_state['num_names']; $i++) {
   $form['name_' . $i] = array(
     '#type' =&gt; 'textfield',
     '#title' =&gt; 'Value ' . $i,
     '#required' =&gt; true
   );
 }

 $form['add_button']= array(
  '#type' =&gt; 'submit',
  '#value'=&gt; 'Add more',
  '#ajax' =&gt; array(
    'callback' =&gt; 'campaign_new_form_callback',
    'method' =&gt; 'replace',
    'effect' =&gt; 'fade',
    'wrapper' =&gt; 'form-wrapper',
 ),
);

 return $form;
}

function campaign_new_form_callback($form, &amp;$form_state){
  $form_state['num_names']++;
  $form_state['rebuild'] = true;
  return $form;
}


It always renders two fields. What is the problem in my code?
Setting the rebuild in the ajax callback will not work, as the form has already been built at that point. It needs to be set in a submit function, which is fired before the form is built. You also need to increment your counter in the submit function for the same reason - if you do it in the ajax callback, the form is already built so the increment is not saved. It needs to be done in the submit function.

function campaign_new_form_submit($form, &amp;$form_state)
{
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
}