Form API + AJAX - Form doubles itself on submit I've been looking for an answer to this for hours now.

A) No matter what I do, the form will always be visible again after submit. How can I stop the from from displaying after a successful submit? 

B) If there are validation errors, the form will attach to the existing form, resulting in 2,3,4,5,.. forms on the page. How to stop that? 

This is the code:

function agals_support_form($form, &amp;$form_state) {
$form['wrapper'] = array("#markup" =&gt; "&lt;div id='status'&gt;&lt;/div&gt;");

$form['name'] = array(
  '#type' =&gt; 'textfield',
  '#title' =&gt; t('Name'),
  '#default_value' =&gt; '',
  '#maxlength' =&gt; '128',
  '#required' =&gt; TRUE,
);

$form['submit'] = array(
  '#type' =&gt; 'submit',
  '#value' =&gt; t('submit'),
  '#ajax' =&gt; array(
    'callback' =&gt; 'agals_support_form_ajax_handler',
    'effect' =&gt; 'fade',
    'wrapper' =&gt; 'status',
  ),        
);

if(isset($form_state['values']['name'])) { //output 
  $form['form_output'] = array(
    '#prefix' =&gt; '&lt;p&gt;',
    '#suffix' =&gt; '&lt;/p&gt;',
    '#markup' =&gt; t('You entered @value', array('@value' =&gt; $form_state['values']['name'])),
  );
} } return $form; }




function agals_support_form_submit(&amp;$form, &amp;$form_state) {
  watchdog('agals_support', 'submitted');  
  drupal_set_message('Form submitted');
  $form_state['rebuild'] = TRUE;
}

function agals_support_form_validate(&amp;$form, &amp;$form_state) {
  watchdog('agals_support', 'validation');
  if (empty($form_state['values']['name'])) {
    watchdog('agals_support', 'name missing');  
    form_set_error('name', t('Please enter your name.'));
  }
}

function agals_support_form_ajax_handler(&amp;$form, &amp;$form_state) {
  watchdog('agals_support', 'ajax_handler');
  return $form;
}
The issue you are facing is that you are not wrapping your form with the wrapper div, you're prepending a div to your form. When the ajax form is loaded, it is inserted into this wrapper div, rather than replacing the contents of the form.

Change this:

$form['wrapper'] = array("#markup" =&gt; "&lt;div id='status'&gt;&lt;/div&gt;");


To this:

$form["#prefix"] = "&lt;div id='status'&gt;";
$form["#suffix"] =&gt; "&lt;/div&gt;";


This will wrap your form in the #status div.