Friday, November 6, 2009

How to use AJAX in DRUPAL

How to use AJAX in DRUPAL

We can easily use AJAX in DRUPAL framework. Drupal provide the jQuery javascript library so we can use jQuery for our AJAX implementation. First we write a module in which we are going to implement the server side logic. Suppose our module name is product and we will check the given product name is exist or not in our product table.

<?php
/*product.module*/
 
function product_menu() {
   $items = array();
 
 $items['product'] = array(
  'page callback' => 'drupal_get_form',
  'page arguments' => array('product'),
      'access arguments' => TRUE,
      'type' => MENU_CALLBACK,
   );
 
   $items['product/check_name'] = array(
      'page callback' => 'check_name',
      'access arguments' => TRUE,
      'type' => MENU_CALLBACK,
   );
 
   return $items;
}
 
function product() {
 $path = drupal_get_path('module', 'product');
 drupal_add_js($path . '/product.js', 'module');
 
 $form['product_name'] = array(
  '#title' => t('Product Name'),
  '#type' => 'textfield',
  '#required' => TRUE,
  '#size' => 30,
  '#description' => t('Please enter product name.'),
 );
 
 $form['check_name'] = array(
  '#type' => 'markup',
  '#value' => "" . t('Check Product Name') . "
", ); $form['status'] = array( '#type' => 'markup', '#value' => "
", ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Submit'), ); $form['cancel'] = array( '#type' => 'markup', '#value' => l(t('Cancel'), 'product_mgmt'), ); return $form; } function check_name() { $name = strtolower($_GET['name']); $query = "SELECT COUNT(*) AS total FROM {product} WHERE LOWER(product_name) LIKE ('%s')"; $rs = db_query($query, $name); $info = db_fetch_object($rs); $total = $info->total; if ($total) { echo "$('#status').html('This product is available.');"; } else { echo "$('#status').html('This product is not available.');"; } } ?>

Don’t return anything in “check_name()” function otherwise it will return the whole page when we access “product/check_name” path through AJAX.

/*product.js*/
 
// JavaScript Document
$(document).ready(function() {
 $('#check_name').attr('href', 'javascript:void(0);');
 
 $('#edit-product-name').keydown(function(event){
  $('#status').html('');
 });
 
    $('#check_name').click(function() {
  var name = $.trim($('#edit-product-name').val());
 
  if (name == '') {
   $('#status').html('Please enter product name.'); return;
  }
 
  $.ajax({
      type: "GET",
   url: "/product/check_name",
      data: "name=" + encodeURI(name),
      success: function(msg){
    eval(msg);
      }
   });
 });
});

No comments: