Jquery – Ajax loading node fields in drupal with jQuery


Right now I'm loading nodes with jquery's $.ajax. By that I mean I simply enter in the node url and then load the whole page.

That's probably ridiculous and totally incorrect way to do it. How do I fetch a specific field in a node without loading the kitchen sink?


I also see this module:


Am I to use that?

Edit: An example of what I'm doing is like this:

    url: node/500,
    success: function(response){
        var ajaxresult = $("<div/>").append(
        response.replace(/<script(.|\s)*?\/script>/g, "").find('#field-want-this-field').html();

This loads the entire page first, and then grabs the field. Since it's on the same site, surely there's a better method?


Best Solution

What you are doing is a waste, but it will require a bit of work to get this to work. What need to do, is to setup a function that can make the queries for what you need, fx one that would take the node id and field name and then return the field text. There are two ways of doing this.

  1. node_load (slow but simple)
  2. querying the db directly for the field that contains the data (fast but more complicated)
One problem is general, is that fields sometimes use delta if there are more than one value for the same field. This makes it a bit more complex to get the data you need. This is also decided through the admin interface which means a site admin could possible break this functionality if you don't take care. Another thing is that the names of the fields also is created through the admin interface (unless you have created a node type with some fields in your own module).

Then thing that makes querying the db yourself difficult, is that CCK have different ways of making tables to save the data in, and you have to figure out exactly how this works, to make this generic.

In the end, if you create your own function you could do something like this:

function get_date($args) {
    // get the data as $data
    return drupal_json $data;

and your ajax.

$.getJSON('mymodule/node/nid/field_name', function(php_data) {

Drupal will cache your get requests, so you have to use different urls to take advantage if that.