For Drupal 7 you can use the below code
/**
* Implements hook_menu().
*/
function hook_menu() {
$items['test_ajax'] = array(
'title' => 'test ajax',
'page callback' => 'drupal_get_form',
'page arguments' => array('demo_form'),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
....
}
/**
* Implements hook_form().
*/
function demo_form($form, &$form_state) {
return array(
'email' => array(
'#type' => 'textfield',
'#title' => t("Join our Newsletter"),
'#required' => TRUE,
'#attributes' => array(
'placeholder' => t("[email protected]")
),
),
'submit' => array(
'#type' => 'submit',
'#value' => t('Subscribe'),
'#ajax' => array(
'callback' => 'demo_form_ajax_submit',
'wrapper' => 'demo-form',
'method' => 'replace',
'effect' => 'fade',
),
),
);
}
/**
* Ajax callback function.
*/
function demo_form_ajax_submit($form, $form_state) {
drupal_set_message();
$message = '';
if (!empty($form_state['input']['email'])) {
if (valid_email_address($form_state['input']['email'])) {
$message = "subscription successful!!!";
$status = 'status';
}
else {
$message = 'Please enter valid email ID!!';
$status = 'error';
}
drupal_set_message($message, $status);
}
$form_state['rebuild'] = TRUE;
return $form;
}