Archive for May, 2010

How know Base Path of Drupal in JavaScript

Sometimes you want to know about the Base Path of your Drupal installation in JavaScript. You may want to know about this path for sending the AJAX request at correct URL relatively, load the image or some other type of file on client side through JavaScript etc.

Drupal provide a variable called Drupal.settings.basePath for this purpose in JavaScript. But this variable is only available if you include any custom JavaScript file or JavaScript block in your module. By default Drupal doesn’t include the ‘jquery.js‘ and ‘drupal.js‘ file in generated output. It only add these files if you add your custom JavaScript file or JavaScript block. We can include our custom JavaScript file in Drupal like this:-

drupal_add_js(drupal_get_path('module','my_module'). '/my_module.js');

The my_module.js file should reside in same directory where my_module module exist. This will force Drupal to add jquery.js and drupal.js files in output.

These two files initialize the Base Path variable. In drupal.js file, on top you can see the initialization of setting object in Drupal object. Like this:-

var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'themes': {}, 'locale': {} };

Drupal generate some JavaScript code in Script block inside head tag of each page for extending the settings object with the help of jQuery. Like this:-

jQuery.extend(Drupal.settings, { "basePath": "/" });

You can test the Base Path by adding following code in my_module.js file.

$(document).ready(function() {
	alert(Drupal.settings.basePath);
});

This will alert the Base Path for Drupal installation after loading of the page.

, ,

No Comments