Ajax with Drupal callbacks
- May 29th, 2011
- Posted in articles
- By Ionut
- Write comment
In this short article I would like to explain how to create a simple AJAX request handler in Drupal.
So you have a module created, and you would like to add some AJAX requests in a page, but the question is where to point the requests to? What you have to do is create a Drupal callback, that you can use in a AJAX request, and that will return just the data you need in the callback.
To create a Drupal AJAX callback we need to add a hook_menu in our module, and there declare a callback, like this:
-
$items['admin/settings/test'] = array(
-
'page callback' => 'test_function',
-
'type' => MENU_CALLBACK,
-
'access arguments' => array('access content'),
-
);
And now in our test_function we can return whatever data we need, for example:
-
function test_function()
-
{
-
echo json_encode(array('output'=>'test'));
-
}
So now we can point to ‘/settings/test’ in our AJAX request.
If we are using a language module then we should call the AJAX callback after passing it through the Drupal url function:
-
<?=url('admin/settings/test')?>
to have the correct language set in the callback. So if german is selected, we would have ‘/de/settings/test’.
No comments yet.