[Drupal] How to use ajax_command_replace?

| | 2 min read

To replace a div by another on submitting a form always used to top the list of requirements. So I've choose to share how to use a handy command provided by ajax to replace a particular div by another.

Let us consider having a form, on submitting the form let it replace the form by a successful message. To do this, 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',
      ),
  );
function sample_ajax_form_callback($form, &$form_state) {
    $commands = array();
    $output = '<div id = "div-example">' . 'Your form submitted successfully' . '</div>';
    $commands[] = ajax_command_replace('#div-example', $output);
    $element = array(
      '#type' => 'ajax', 
      '#commands' => $commands
    );
    return $element;
  }

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.

On the callback, the div containing form that is, div-example is wrapped around the message we want to display instead of the form after submitting it.

After submitting the form you could see a success message. Hope some one would find this article helpful. Please let us know if we can be of any further help.