Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Drupal 7 — Basic Ajax form submit (Ajax framework)
<?php
/**
* @file
* Demo module, Basic Ajax form submit (Ajax framework).
*/
/**
* Implements hook_menu().
*/
function demo_menu() {
return array(
'demo/newsletter' => array(
'page callback' => 'drupal_get_form',
'page arguments' => array('demo_demo_form'),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
),
);
}
/**
* A simple newsletter subscribe form.
*/
function demo_demo_form($form, &$form_state) {
return array(
'email' => array(
'#type' => 'textfield',
'#title' => t('Join our Newsletter'),
'#required' => TRUE,
'#attributes' => array(
'placeholder' => t('mail@example.com'),
),
),
'submit' => array(
'#type' => 'submit',
'#value' => t('Subscribe'),
'#ajax' => array(
'callback' => 'demo_form_ajax_submit',
'wrapper' => 'demo-demo-form',
'method' => 'replace',
'effect' => 'fade',
),
),
);
}
/**
* Ajax callback function.
*/
function demo_form_ajax_submit($form, $form_state) {
// Dummy/dumb validation for demo purpose.
if (!empty($form_state['input']['email'])) {
return 'Subscribed !';
}
else {
return $form;
}
}

fat763 commented Apr 17, 2013

Realy easy (: thanks a lot!

dskanth commented Nov 6, 2014

Works great... I slightly modified the AJAX response to:
return 'Dear '.$form_state['input']['email'].', you are Subscribed!';

visor09 commented Nov 25, 2015

Thanks for the example

gembes commented Aug 4, 2016

thank for good example..

Thanks a lot, this is exactly what i was looking for.

very good example... but i can't make it to work if i add to my fields there something like:

'onChange' => 'this.form.submit();'

my wish would be to auto submit the form when values are changed, plus make this an ajax form :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment