proper way to handle drupal hook_submit from jquery $.ajaxform() calls

Events happening in the community are now at Drupal community events on www.drupal.org.
calebtr's picture

I'm adding a from to allow users to change a node's taxonomy without going to the edit page, similar to the community tags module, except with a controlled vocabulary instead of free tagging.

I built the form in a custom module and made sure all the hooks worked. Then I added the call to JQuery's .ajaxform() function. It works beautifully except that I want to apply some effects after the changes, so I wanted a different, JSON-y response if the call was from Ajax, rather than if it was a usual http request from the browser.

I am getting the sense that this is exactly what the Ajax module's API is for and I'm poking around there, but I thought I would ask here to see if I was on the right track.

To Ajaxify a form and still keep it working, I:

  • add a hidden element to the form ie

  $form['my_form_js'] = array (
    '#type' => 'hidden',
    '#default_value' => 0,
  );
  • change the value when the page loads

if (Drupal.jsEnabled) {
  $(document).ready(function(){
    $('#edit-my-form-js').val(1);
    $('#my-form').ajaxform(function () {
...
  • in hook_submit, return one type of data for a normal submit and another type for an ajax submit. This is the part I'm wondering about most - is it reasonable to call exit after returning json, or am I doing something un-drupally? The idea is to stop hook_submit from sending the re-loaded page back with the JSON data.

function my_form_submit($form,&$form_state) {
  my_do_some_dirty_work();
  if ($form_state['values']['my_form_js']) {
    drupal_json(array('reply' => 'Ok!'));
    exit;
  }
  drupal_set_message('Ok!');
  return;
}

Thanks!

Javascript

Group notifications

This group offers an RSS feed. Or subscribe to these personalized, sitewide feeds: