Using Ajax in Drupal6 Select Box

Using Ajax in the Drupal is so easy but can be a little work around at the beginning. In this post I will go with the technique of how we can deploy the Ajax in Drupal Form in our custom module using Jquery , Drupal Api .
Basic Steps

Create a page using Drupal Hook_Menu().Put this code in you modules ‘.module’ file .

// create the page which will be called asynchronously by the client script (AJAX). 
function MYMODULE_menu() {
      // url of the page will be 'http://your_drupal_project/ajax_page'
      $items['ajax_page'] = array(
            'page callback' =>'my_content',
            'type' => MENU_CALLBACK,
            'access arguments' =>array('access content'),
      );
      return $items;
}
// content for the page , outputs the json object of the required information 
function my_content($category_id){ 
        $options = array(); 
	$sql = 'select * from my_table'; 
	if (!empty($category_id)){ 
		$sql .= " where category_id = '".$category_id."'"; 
	}  
	$result = db_query($sql); 
	while($row = db_fetch_object($result)) {
		$options[$row->product_id] = $row->product_name;
	} 
        if (!count($options)) $options['empty'] = true; // if the query returns no data 
	drupal_json($options); 
 }

Now lets suppose we have the block of the form or we can create like this .

// create a block using the drupal 'hook_block' api 
function MYMODULE_block($op = 'list', $delta = 0, $edit = array()) {
  $block = array();
  // we need javascript for Ajax request and Json object manipulation so call the javascript 
  drupal_add_js(drupal_get_path('module', 'MYMODULE') . '/MYMODULE.js');
  switch ($op) {
    case 'list':
      $block[0]['info'] = t('Drupal ajax select box');
	   break;
    case 'view':
      switch ($delta) {
        case 0:
          $block['subject'] = t('Drupal ajax select box');
          $block['content'] = drupal_get_form('my_form');// renders the from we created
          break;
      }
      break;
  }
  return $block;
}
// now create the form 
// here i have assume only two form elements with product and category information .
function my_form(){ 
  $form = array();
  $form['product_category'] = array(
    '#type' => 'select',
    '#title' => t('Product Category'),
    '#required' => FALSE,
    '#options'=>array(
	     '' =>'Select Category',
		 '1'=>'Category1',
		 '2'=>'Category2',
		 '3'=>'Category3',
	),
    '#attributes'=>array('id'=>'product_category'),
  );
  $form['product_name'] = array(
    '#type' => 'select',
    '#title' => t('Product Name'),
    '#required' => FALSE,
    '#options'=>array(
		 '' =>'All Product',	
	         '1'=>'Product1',
		 '2'=>'Product2',
		 '3'=>'Product3',
	),
    '#attributes'=>array('id'=>'product'),  
  );
  return $form;
}

Now its turn to create the Javascript file which has been already called on above drupal ‘hook_block’ api . On this Javascript file we will assign the event to that form element which will make AJAX request to get its child form elements options. In our case category select box will make AJAX request and fetch the product accordingly .Create the javascript file name as MYMODULE.js on your module folder.

jQuery(document).ready(function(){ 
	var Change_Option = { 
		Requesting_Element: $('#product_category'),
		Changing_Element  : $('#product'),
		Page	: "ajax_page/",
		_Ajax: function(){ 
			 this.Changing_Element.attr('disabled','disabled'); 
			 this.Ajax_Call(); 
		},
		Get_Argument:	function(){ 
			return  this.Requesting_Element.val(); 		
		},
		Ajax_Call: function(){ 
			var Self = this;
			$.get( this.Page+this.Get_Argument(), null, function(json_response){ 
				Self.Create_Option(json_response); 
				Self.Changing_Element.removeAttr('disabled'); 
			}); 
		}, 
 
		Create_Option:function(_json_response){ 
			 var _Json = Drupal.parseJson(_json_response);
			 if(_Json.empty){ 
				this.Changing_Element.html(this.Create_Option_Node('','No product')); 
			 }else {  
				 if (this.Get_Argument() == '') 
					this.Changing_Element.html(this.Create_Option_Node('','All Product'));
				 this.Changing_Element.html('')
				 for (i in _Json ) { 
					this.Changing_Element.append(this.Create_Option_Node(i,_Json[i]));
 
				 }
			 } 
		},
		Create_Option_Node:function(value,html){ 
			var _option = document.createElement('option');
			_option.value =  value; 
			_option.innerHTML = html;
			return _option; 
 
		},
		Create_Effect:function(){
			Change_Option._Ajax();
		}
 
	}
	Change_Option.Requesting_Element.change(function(){ 
		Change_Option.Create_Effect(); //event handler
	}); 
});

I hope this helps for the Drupal newbie. If you have any problem with the above scripts, please feel free to throw comments or contact me with the contact box.
I think the above Javascript easy enough to customize as I have followed javascript OOP approach.

1,600 views
Drupal, Javascript, Jquery, Php

Comments

One Response to “Using Ajax in Drupal6 Select Box”

Leave Comment

(required)

(required)