How to Use Drupal’s db_query() With AJAX Calls

I recently had a scenario on a Drupal 6 site that I am developing where I wanted to refresh some content every 10 seconds with new data from the Drupal database. Usually to do something like this I do the following:

  • Use an AJAX call to a PHP script on my site.
  • PHP script queries database and sends back the response.

You can’t do this though if you want to use Drupal’s API since Drupal needs to go through it’s entire boot process before any of the API is avaible. Luckily there is an easy way to get around this; create a module with a menu hook.

To create the module first create the .info file:


;custom_ajax.info
name = Custom Ajax Calls
description = Allows AJAX to use Drupal API
core = 6.x
project = "custom_ajax"

Next create the module file with the hook_menu() and call back.


// custom_ajax.module

// menu hook call
function custom_ajax_menu()
{
// List of navagation links to your ajax functions.
$items = array();

// Creates a link yoursite/?q=my/ajax/function that will call the page callback function (custom_ajax_my_ajax_function())
$items["my/ajax/function"] = array(
"title" => t("title"),
"description" => t("provides access to a php function that can be requested by an ajax call"),
"page callback" => "custom_ajax_my_ajax_function",
"access arguments" => array("access content"),
"type" => MENU_CALLBACK
);
}

// The function that actually does what you need for the ajax request
function custom_ajax_my_ajax_function()
{
$q = "";
db_query($q); //drupal api
echo json_encode($data);
exit; // Don't render the page.
}

Now in your JavaScript code, you just make the AJAX request to the callback path


$.ajax({
url:'/?q=my/ajax/function',
success: function(data, success, jqXHR){
}
});

Leave a Reply

Your email address will not be published. Required fields are marked *