Drupal 7 – Simple Ajax implementation @ 1

In this post, i will show you how to implement a simple Ajax function in Drupal 7. The following example code is based on the blog post written by Kevin Hankens about implementing Ajax in Drupal 6.
Kevin Hankens’s blog – Drupal, jQuery and $.ajax() easyness

What i am going to do is the same as Kevin’s example. But for simplicity, i removed the access control logic so all content is visible to anonymous users.

So let’s create a custom module with folder name eureka_ajax.
eureka_ajax.info

name = Eureka Ajax
description = Simple Ajax example in Drupal 7 by ykyuen
core = 7.x
package = Eureka

 

eureka_ajax.module

<?php
/**
 * Implementation of hook_init().
 */
function eureka_ajax_init() {
  // Include the js file
  drupal_add_js(drupal_get_path('module', 'eureka_ajax') . '/eureka_ajax.js');
}

/**
 * Implementation of hook_menu().
 */
function eureka_ajax_menu() {
  $items = array();

  // Create a Drupal page to display our AJAX link.
  $items['eureka/page'] = array(
    'title' => 'Test Page',
    'page callback' => 'test_page_callback',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );

  // Create a path to send our AJAX request to.
  $items['eureka/ajax'] = array(
    'title' => 'Ajax Request',
    'page callback' => 'ajax_request_callback',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Callback function for /eureka/page.
 */
function test_page_callback() {
  return theme('ajax_link');
}

/**
 * Implementation of hook_theme().
 */
function eureka_ajax_theme() {
  return array(
    'ajax_link' => array(),
  );
}

/**
 * Implementation of theme_ajax_link().
 */
function theme_ajax_link() {
  return l(t('What is the date and time?'), 'eureka/ajax', array(
    'attributes' => array(
      'id' => 'eureka-ajax')
    )
  );
}

/**
 * Callback function for /eureka/ajax.
 */
function ajax_request_callback() {
  if ($_POST['from_js']) {
    // Return the time if the from_js request para is set to true
    $response = array(
      'message' => t('It is approximately !date', array('!date' => date('M j Y h:i:s'))),
    );
    drupal_json_output($response);
    exit;
  } else {
    // Return an empty json array for incorrect request
    drupal_json_output(array());
    exit;
  }
}

 

eureka_ajax.js

(function ($) {
  Drupal.behaviors.eurekaAjax = {
    attach: function (context, settings) {
      // Bind an AJAX callback to our link
      var eurekaAjaxLink = $('#eureka-ajax');
      
      eurekaAjaxLink.click(function(event) {
        // Prevent the default link action
        event.preventDefault();
        
        // Get the request URL without the query string
        var ajaxUrl = eurekaAjaxLink.attr('href').split('?');
        
        $.ajax({
          type: "POST",
          url: ajaxUrl[0],
          data: {
            // For server checking
            'from_js': true
          },
          dataType: "json",
          success: function (data) {
            // Display the time from successful response
            if (data.message) {
              $(".messages").remove();
              $("#content").prepend('<div class="messages status">' + data.message + '</div>');
            }
          },
          error: function (xmlhttp) {
            // Error alert for failure
            alert('An error occured: ' + xmlhttp.status);
          }
        });
      });
    }
  };
})(jQuery);

 

Enable the module, clear the cache and then browse http://<drupal>/eureka/page.

 

Click the link and see what you get.

 

Done =)

Next: Drupal 7 – Simple Ajax implementation @ 2

Reference:

Update @ 2012-09-07: This example does not work in Garland theme. Please use the default Bartik theme for trial. Thanks Jack.

About these ads

9 thoughts on “Drupal 7 – Simple Ajax implementation @ 1”

  1. hello, thank you for this simplified example.
    i have a little probleme, it works really well but the message appears only after a refresh of the page. that page opens in a lightbox, i hope not that the lightbox is the problem…
    thanks
    markus

    Like

    1. I believe that should be related to the lightbox. how do u implement the lightbox?

      and I think you could spend some effort on the success callback in eureka_ajax.js. That part is responsible for the action after retrieving the time thru the ajax call.

      Like

  2. Doesn’t work with garland theme, so if you are testing this module and the message does not appears, first you should change your drupal theme, for example, to bartik, then you’ll be able to play around with this code.

    Like

  3. Very good example but it’s very simple. Suppose that you load a node via jquery Ajax and in that node there is an image which pop up with a lightbox. With your technique it looses this lightbox behavior. Or a form that submits with Ajax, The form also lose the Ajax submit.

    Have you figured out how to do that? If so, can you make an example with that?

    Thank you!

    Like

    1. About the lightbox on ajax content, you need to re-initialize the lightbox on the image link. For more information, you could refer the following 2 links.

      About the ajax form, how could you bundle the form with the node content?

      The simplest way i think of is to implement the ajax form using the same approach in this example. you could create the url for the ajax action and implement the whole ajax workflow without using the Drupal Ajax form API.

      Like

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