Drupal : Three simple steps to adding ajax to your drupal forms/pages

If you need a simple content refresh system, let me show you an example of a simple (yet powerful) implementation.

Step 1
Download a the lightweight ajax library from ImpliedByDesign, and copy it to a directory called “ajax” in your module directory.

Step 2
Add the following two functions to your drupal module

function printAjaxJs() {
   drupal_add_js(drupal_get_path('module', 'myModule').'/ajax/ajax.js');
}
function printAjaxFunction($function,$page) {
  $output.='function '.$function.'(div_id,content_id) {';
  $output.='subject_id = div_id;';
  $output.='content = document.getElementById(content_id).value;';
  $output.='http.open("GET", "'.$page.'" + content, true);';
  $output.='http.onreadystatechange = handleHttpResponse;';
  $output.='http.send(null);';  $output.='}';
  drupal_add_js($output,'inline');
}   

Step 3
Ajaxfy your forms/pages

  printAjaxJs();
  $function="showContent";
  printAjaxFunction($function,"/show/content/");
  $script=$function."('updated-field','edit-myselect')";
  $form['myForm']['mySelect'] = array(
  '#type' => 'select',
  '#title' => t('Formation Select'),
  '#default_value' => $fdefault,
  '#options' => $foptions,
  '#prefix' => '
', '#suffix' => '
The output of /show/content/*value* will be updated here.
', );
Advertisements

One thought on “Drupal : Three simple steps to adding ajax to your drupal forms/pages

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s