Dev:Using AJAX

From Habari Project

Jump to: navigation, search

AJAX lets a browser send and receive data to and from a server without reloading the web page. This page describes how use AJAX in your Habari plugins. Note that AJAX is not available for themes.

Adding AJAX to your Site

jQuery, which comes bundled with Habari, has a useful API that makes implementing AJAX in the browser simple. There are plenty of good tutorials on the Web, and you can read more about adding Javascript.

To integrate AJAX with Habari, you need to set up a URL for accepting AJAX calls, and provide a method in your plugin to process those calls.

You can use URL::get() to create an appropriate URL. The context parameter determines the method of your plugin that will be called when an AJAX request is sent to that URL.

 * Add required Javascript
public function theme_header($theme)
  // Add the jQuery library
  Stack::add('template_header_javascript', Site::get_url('scripts') . '/jquery.js', 'jquery');
  // Add Javascript to perform the AJAX.
  // This would probably be done in an external file.
  $js = <<<JS
	fileManager = function(){};
			{'action': 'Ponies!'},
  Stack::add('template_header_javascript', $js, 'file_manager', 'jquery');
  // Add the callback URL.
  $url = 'fileManager.url=\''.URL::get('ajax', array('context' => 'file_manager')).'\'';
  Stack::add('template_header_javascript', $url, 'file_manager_url', 'file_manager');
 * Respond to Javascript callbacks
 * The name of this method is action_ajax_ followed by what you passed to the context parameter above.
public function action_ajax_file_manager($handler)
  // Get the data that was sent
  $response = array($handler->handler_vars['action']);
  // Wipe anything else that's in the buffer
  // Send the response
  echo json_encode($response);

Using AJAX in Habari's Admin

If you're adding AJAX in Habari's admin interface, it's likely that requests should only be allowed when the browser is authenticated. You can do this by using auth_ajax instead of ajax.

$url = 'fileManager.url=\''.URL::get('auth_ajax', array('context' => 'file_manager')).'\'';
Stack::add('admin_header_javascript', $url, 'file_manager_url', 'file_manager');

Similarly, the callback method would be called action_auth_ajax_file_manager.

To encourage consistency when making AJAX calls in the admin area, Habari provides the habari_ajax Javascript object and the AjaxResponse class.

Personal tools