How to emulate all the AJAX functionality when the form is rendered after an AJAX callback? I have a Drupal form, but I am adding it to the page as the result of an AJAX callback.

I need this form to trigger a new callback. My code below:

      $form['#suffix'] = '&lt;div id="form-return-message-box"&gt;this is the return box&lt;/div&gt;';
  $form['#attached']['js'] = array('misc/ajax.js');

  $form['markup'] = array(
    '#type' =&gt; 'markup',
    '#markup' =&gt; '&lt;h2&gt;This is a form&lt;/h2&gt;'
  );


  $form['button'] = array(
    '#type' =&gt; 'button',
    '#value' =&gt; t('Submit'),
    '#ajax' =&gt; array(
      'callback' =&gt; 'module_myform_callback',
      'wrapper' =&gt; 'form-return-message-box',
      'method' =&gt; 'replace',
      'effect' =&gt; 'fade',
    ),
  );

  $replace_layer = '#somelayer';

  $commands = array();
  $commands[] = ajax_command_replace($replace_layer, drupal_render($form));
  $page = array(
    '#type' =&gt; 'ajax',
    '#commands' =&gt; $commands,
  );

  ajax_deliver($page);


So this is what happens: this form is being added into a container called 'somelayer' that already exists on the page (I didn't add that part of the code because I thought it would be unnecessary). It was called from a link with the class 'use-ajax'.

So the form renders on the page as desired after an AJAX callback triggered by the link.  This part works allright.

But here is the (very) tricky part: I would also like to preserve the new form AJAX functionality (check the '#ajax' part of the array), which doesn't occur. After the form is rendered, the button won't trigger any AJAX code. By clicking on it, the page will refresh, not triggering the callback function (not added here to preserve space).

By looking into source code of a regular form page with AJAX, you will see code like this that enables the AJAX functionality: 

"ajax":{"edit-something":{"callback":"module_formname_callback","wrapper":"wrapper-name","method":"replaceWith","effect":"fade","event":"change","url":"\/spabear\/system\/ajax" ...


By looking at the source code of the form added into my page, I can see there is no piece of &lt;script&gt;&lt;/script&gt; code that would trigger the AJAX callback in my dynamically loaded form. How can I emulate all the AJAX functionality when the form is rendered after an AJAX callback?
The #ajax['wrapper'] property includes the HTML ID of a page section that should be replaced (or altered in some other way).
The #ajax['callback'] tells the Form system what callback should be called after the Ajax call happens and the form is rebuilt.

https://www.drupal.org/docs/7/api/javascript-api/ajax-forms-in-drupal-7