How to create a simple Ajax call in Drupal 7

Drupal ajax calls

The following is a mini tutorial about Drupal and Ajax. You can improve your site using ajax calls using the hook_module and jQuery load function.

Define a link to execute the Ajax call

This is very basic, you have to create a element to set the ajax call. For example:

  <button type="button" class="my-button-class">Ajax test</button>

Also you need an element to receive the Ajax callback:

  <div class="my-div-class">Ajax result</div>

Then, you need to set the event of the button and, of course, load the url of your content.

  $('.my-button-class').on('click', function() {
    $('.my-div-class').load('/ajax/get-user/');
  });

Using hook_menu

You note that the url /ajax/get-user/ does not exists in your Drupal site, you have to set this url in your custom module via hook_menu.

function your_module_name_menu() {
  $items['ajax/get-user/'] = array(
    'title' => 'Get current user'
    'page callback' => 'your_module_name_ajax',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content')
  );

  return $items;
}

Also you need to create your new function defined above:

  function your_module_name_ajax() {
    global $user;
    $user_name = $user->name;

    drupal_json_output($user_name);
  }

The your_module_name_ajax function gets the current username and print the name. It's very basic, but of course you can add your custom behavior.