Attaching behaviors to ajax button in JSON outputted form

As great as Drupal is, there are certain occassions when the power of Drupal is not documented well enough. During the course of our module development, we ran into an issue where we wanted to load an ajax form in a dialog which was being outputted via json. The problem was simple, the ajax button was not submitting via ajax!

Ajax Form

Every time we clicked the ajax submit button, it would submit like a normal button and would take us to the same form on another page. The issue was perplexing.

The code that outputted the form looked like this:

  $json['html'] = drupal_render(drupal_get_form('my_form'));

We made sure that we attached behaviors to the ajax button via jquery like this:

$('a.my_link', context).click(function() {
//Processing done here
}, "json");

However, it didn't work. We were sure that we were missing some vital piece of code that was not documented well enough in Drupal. We finally found the solution. We needed to explicitly set the settings for the browser before we outputted the form.

  //Retrieve the HTML generated from the $form data structure.
  $html = drupal_render(drupal_get_form('myform'));
  $javascript = drupal_add_js(NULL, NULL);
  $settings = FALSE;
    $settings = '<script type="text/javascript">jQuery.extend(Drupal.settings, ' .
    drupal_json_encode(call_user_func_array('array_merge_recursive', $javascript['settings']['data'])) .
  //Add the settings to the form
  $html .= $settings;
  //Print the form
  print $html;

Voilà!! That was it. Our form was opening in a new dialog and our ajax button in the form was submitting via ajax, just as we hoped. All it took was a few lines of code. We hope this little snippet here has enlightened you just a little bit and hopefully, will prove to be useful in the future.