Skip to content

Instantly share code, notes, and snippets.

@pascalduez
Created December 24, 2011 11:49
Show Gist options
  • Save pascalduez/1517190 to your computer and use it in GitHub Desktop.
Save pascalduez/1517190 to your computer and use it in GitHub Desktop.
Drupal 7 — Basic Ajax request (manual)
/**
* @file demo JS.
* jQuery 1.5+
*/
(function( $ ) {
// On DOM ready
$(function() {
var content = $("#block-system-main").find(".content")
, link = $("#demo-ajax-link")
, req
link.click(function( e ) {
e.preventDefault()
req = $.ajax("/demo/ajax", {
dataType: "json",
type: "GET"
})
req.done(function( data, textStatus, jqXHR ) {
content.append( data.data )
})
req.fail(function( jqXHR, textStatus, errorThrown ) {
})
req.always(function( jqXHR, textStatus ) {
})
})
})
})( jQuery );
<?php
/**
* @file
* Demo module, Basic Ajax request (manual).
*/
/**
* Implements hook_menu().
*/
function demo_menu() {
return array(
'demo/page' => array(
'page callback' => 'demo_page_callback',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
),
'demo/ajax' => array(
'page callback' => 'demo_ajax_callback',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
'delivery callback' => 'demo_ajax_delivery_callback',
),
);
}
/**
* Demo page callback.
*/
function demo_page_callback() {
$path = drupal_get_path('module', 'demo');
drupal_add_js($path . '/demo.js');
$output = '<p>This is an ajax demo link: ';
$output .= l('Click me ! ', 'demo/page', array('fragment' => 'nojs', 'attributes' => array('id' => array('demo-ajax-link'))));
$output .= '</p>';
return $output;
}
/**
* Demo Ajax callback.
*/
function demo_ajax_callback() {
$response = array(
'status' => 1,
'data' => 'Hello ! ',
);
return drupal_json_output($response);
}
/**
* Demo Ajax delivery callback.
*/
function demo_ajax_delivery_callback($page_callback_result) {
print $page_callback_result;
ajax_footer();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment