[Drupal] How to incorporate AJAX into a Drupal form?

| | 1 min read

Creating a module by ourselves, or a new requirement by client would let you to learn more, to research more. One of the latest requirement was to AJAXify a form. To do AJAX-ification was always a troublesome for me.

AJAX-fy a custom form

AJAX let us to submit a form without page refresh, but it only handles a little payload. If it can also increase user experience with AJAX forms. These advantages became handy for the AJAX form.

Lets start with a simple example, Here consider a form with name and a submit button.

function sample_ajax_form($form, &$form_state) {
  $form['#prefix'] = '<div id="div-example">';
  $form['#suffix'] = '</div>';
  $form['captcha'] = array(
    '#type' => 'textfield',
    '#value' => t('Name'),
  );
   $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Calculate'),
    '#ajax' => array(
        'callback' => 'sample_ajax_form_callback',
        'wrapper' => 'div-example',
      ),
  ); 

Here we have created a function sample_ajax_form, $form['#prefix'] and $form['#suffix'] represents the div in which the form is included. The form is inclined in div-example. If the form is submitted through ajax, then on the submit button specify #ajax. #ajax is an array that include callback and the div in which the form is embedded.

Drupal has had offered a lot of ways to make it simpler. AJAXifying a form is one of those. To do Ajax on Drupal is much more simple and easier compared to other CMS and langauges.

Please let us know if we can provide any further assistance.