[Drupal] How to implement jquery AJAX tab in Drupal 7?

| | 1 min read

JQuery and AJAX are very useful for loading data into the page without refreshing the web page. AJAX tabs can load content from remote files or URLs. In this example, the content of each Tab will be loaded dynamically with Ajax.

If you want to know how to create quick tab without AJAX, please refer our article how to create quick tab programmatically.

Now, the first step is to write a call back function as,

/**
 * Implements page call back
 */
function menu_call_back() {
  drupal_add_library('system', 'ui.tabs');
  $page['tabs'] = array(
    '#theme' => 'theme_name_tab',
    '#rows' => array(
      'custom_values' => '',
    ),
    '#attached' => array(
      'js' => array(
        drupal_get_path('module', 'module_name') . '/js/custom.js',
      )
  ));
  return $page;
}

Create the file 'custom.js' and add the following codes to your custom.js file

(function ($) {
  Drupal.behaviors.sample_JqueryTabs = {
    attach:function(context, settings) {
      $( "#tabs" ).tabs({
        beforeLoad: function( event, ui ) {
          ui.jqXHR.fail(function() {
            ui.panel.html(
              "Could not load this tab now. We will try to fix this as soon as possible.");
           });
	  }
      });
    } 
  }
});

Create the file 'custom.tpl.php' and add the following codes to your custom.tpl.php file.

<div id="tabs">
  <ul>
    <li><a href="#tabs-1">Preloaded</a></li>
    <li><a href="ajax/content1.html">Tab 1</a></li>
  </ul>

  <div id="tabs-1">
    <p>content here</p>
  </div>
</div>

If you have any further queries, please do contact us. We provide Drupal services to enhance your business potential.