AJAX callback not added using form_alter I want to perform a AJAX callback to check the value of a custom field during user registration. Because the form is already built, I need to use hook_form_alter. 


But, no callback is added using hook_form_alter. Maybe it is overwritten later on? Therefore, I tried $form['#after_build'].
But that fails too for the AJAX property. Adding another form element works perfectly fine.


The code:

/**
 * Implements hook_form_alter().
 */
function member_id_check_v2_form_alter(&amp;$form, &amp;$form_state, $form_id){
  switch ($form_id){
    case 'user_register_form':
    case 'user_profile_form':
      $form['#after_build'][] = '_member_id_check_v2_ajax';
      break;
    default:
      break;
  }
}

function _member_id_check_v2_ajax($form, &amp;$form_state) {
  $form['member_id_check_v2_callback_wrapper'] = array(
    '#type' =&gt; 'textfield',
    '#title' =&gt; t("The default value will be changed"),
  );

  $form['custom_field']['#ajax'] = array(
    'callback' =&gt; '_member_id_check_v2_callback',
    'wrapper' =&gt;  'member_id_check_v2_callback_wrapper',
  );

  return $form;
}

function _member_id_check_v2_callback() {
    watchdog(WATCHDOG_DEBUG,'Callback worked!');
}


What am I missing? Thanks in advance!
You need to do the AJAX callback on #process callback as #after_build callback is too late to inject AJAX.

Check out the this link and the example code:

/**
 * Implements hook_form_alter()
 */
function kf_link_form_alter(&amp;$form, &amp;$form_state, $form_id) {
  if ('example_node_form' == $form_id) {
    //$form['field_link'][$language]['#after_build'][] = '_kf_link_field_link_after_build';
    $form['field_link'][$language][0]['#process'] = array('link_field_process', '_kf_link_field_link_process');
  }
}

/**
 * Custom form api process function
 */
function _kf_link_field_link_process($element, &amp;$form_state, $form) {
  $element['url']['#description'] = '&lt;div id="example-link"&gt;&lt;/div&gt;';
  $element['url']['#ajax'] = array(
    'callback' =&gt; 'kf_link_ajax_callback',
    'wrapper' =&gt; 'example-link',
  );
  return $element;
}

/**
 * Custom ajax callback function
 */
function kf_link_ajax_callback(&amp;$form, $form_state) {
  $values = $form_state['values'];
  $field_link = $values['field_link'];
  $language = $values['language'];
  $url = $field_link[$language][0]['url'];
  $duplicate_nodes = _kf_link_get_url_nid($url);
  foreach ($duplicate_nodes as $duplicate_node) {
    if (isset($duplicate_node-&gt;nid) &amp;&amp; ($duplicate_node-&gt;nid != $values['nid'])) {
      drupal_set_message(t('This URL already exists in &lt;a href="!url"&gt;!title&lt;/a&gt;', array('!title' =&gt; $duplicate_node-&gt;title, '!url' =&gt; "node/{$duplicate_node-&gt;nid}")), 'error');
    }
  }
  $commands = array();
  $commands[] = ajax_command_html(NULL, theme('status_messages'));
  return array(
    '#type' =&gt; 'ajax',
    '#commands' =&gt; $commands,
  );
}