Kurt Jarchow's Blog

January 14, 2009

Drupal, jQuery and the favorite_nodes module

Filed under: Uncategorized — Kurt Jarchow @ 9:41 am

I’ve just completed my first jQuery attempt, to ajaxify the favorite_nodes “add to favorites” link.  Its actually pretty simple.

Edit favorite_nodes/favorite_nodes.module

Find the favorite_nodes_add function, and add the follow just before “return TRUE;”

 if (!empty($_POST['js'])) {
   drupal_json(array(
       ‘is_fav’ => ‘fav-link-’.$nid
    )
  );
exit;
}

Now find the favorite_nodes_link function.  Where ever the $links[] is set (4 occurrences) add attributes:

$links[] = array(’title’ => t(’add to favorites’), ‘href’ => ‘favorite_nodes/add/’. $node->nid, ‘attributes’ => array(’class’ => ‘favorite-link’, ‘id’ => ‘fav-link-’.$node->nid));

Also in that function add the following line at the start of the function to include a js file:

drupal_add_js(drupal_get_path(’module’, ‘favorite_nodes’) . ‘/favorite_nodes.js’);

Next, create the js file in the favorite_nodes dir named favorite_nodes.js and edit it:

 if (Drupal.jsEnabled) {

  $(document).ready(function () {
    $(’a.favorite-link’).click(function () {

      var favSaved = function(data) {
    $(’#'+data.is_fav).html(’Saved’);
      }

    $.ajax({
      type: ‘POST’,
      url: this.href,
      dataType: ‘json’,
      success: favSaved,
      data: ‘js=1′
    });

    return false;

  });

  });
}

This is a quick and dirty way of doing it.  I’m waiting for UI confirmation before I make the interface any better.  The best way of doing it would be instead of changing the innerHTML of the link to “Saved”, you’d change it to “remove from favorites”, and change the link accordingly.  

Passing the ID back to the jQuery got over a problem when there are multiple fav-links on one page.  I’m open to a better solution.

Also I don’t like the placement of the js include file, but I’m not entirely sure where to put it.  

 I didn’t see code for this anywhere else so this might be a good start for anyone interested.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress

Bad Behavior has blocked 86 access attempts in the last 7 days.