Form submit AJAX button not woking after inserting form using AJAX

Versions used: 

I have a page with a link that when clicked loads and inserts an AJAX driven form into the page. When I click to load the form, AJAX does its business and inserts the form into the page, and when I use the form and submit it, it works fine - AJAX processes the form and my use of AJAX commands in the form callback removes the form from the page. However, if I try to reload that same form by clicking the link again, the form loads up but the submit button no longer uses AJAX. The annoying thing was that all the AJAX behaviors were definitely being reattached to the form.

After a bit of digging, it turns out that another form on the page (in this case it was the user switch form from the Devel module), was using the same id on the submit button as the form being loaded, but only when it was loaded the second time. This is because of how Drupal works out the id by remembering ids already used via the drupal_html_id() function. drupal_html_id() only remembers ids by using drupal_static(), so when further processing is done using AJAX to insert the form into the page a second time, the remembered ids are lost.

Solution 1:

What I ended up doing was using object caching in cTools to store the information used by drupal_static() in drupal_html_id() at the end of the page request. Obviously I had to clear/destroy this when the page was reloaded so it could start again. So by doing this, when the form was being loaded the second time around using AJAX, the submit button was using a different id as drupal_html_id() was remembering the id used the first time the form was loaded. I would only use this solution if the form has fields using the same id as other forms being loaded, or if the same form was being used more than once on the same page for some reason, otherwise the solution below is preferable. 

Solution 2:

An easier way of possibly solving this is to change the id of the submit button used in the form. For example:

<?php $form['actions']['submit']['#id'] = 'an-id-that-is-not-edit-submit'; ?>