i've been looking around for a few tutorials on using ajax in modules but most of them involve sending a request and returning the results in JSON. what i want to do is to simply load the html of either a teaser or a full node and get the result returned back as html, without the rest of the template as well.

what would be the best way of doing that? are there any examples or modules to look at as a reference?

Comments

account-deletion-needed’s picture

Without actually trying it out I think you could write your ajax PHP file like this:

// load drupal
chdir($_SERVER['DOCUMENT_ROOT']);
require_once("$_SERVER[DOCUMENT_ROOT]/includes/bootstrap.inc");
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// load node ($nid is the id of the node you wanna load)
$node = node_load($nid);

// theme the node and output the generated HTML
echo theme_node($node, $teaser = false, $page = false);

The actual ajax call can be made using jQuery Javascript code:

$("#id_of_element_where_node_should_be_inserted").load("/my_ajax_script.php");

It's up to you to determin the $nid that should be loaded. You could pass it as a $_POST
variable using the same jQuery load function. For more info check:
http://docs.jquery.com/Ajax

PS: Sorry I just realized this is for Drupal 6 but the code I posted is for Drupal 5. Not sure if it will work there, maybe you
need to look up the Drupal 6 API for similar functions.

dragan_r’s picture

For a Drupal 6 ajax PHP file placed in your root folder could look like this

<?php
// load drupal
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$node = node_load($id);
$node->title = NULL;
print node_view($node);
?>
charlie-s’s picture

Does bootstrapping drupal in this way ignore template files? I am unable to get a themed node using this method (i.e. to include variables added by theme_preprocess_node).

scotthorn’s picture

Anyone know if this method can still see the logged in user, and whether they have permissions to view the node?

charlie-s’s picture

I ultimately ended up with a very small module that has a single menu callback and function to display the node_view:

<?php
function mymodule_menu() {
  $items['node/%/node_view'] = array(
    'page callback' => 'mymodule_get_node',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function mymodule_get_node() {
  $node = node_load(arg(1));
  $node_view = node_view($node);
  print $node_view;
  exit();
}

This will play nice with the currently logged in user. Mess with the 'access arguments' to only allow this for certain users. I use an ajax callback to hit this url and bring in node data on demand.

aaesis’s picture

Is there easy way to use load node using ajax ang i am using drupal 7 now. Every time i click my menu something like div will change and also the node_url wil change also..