How to flag a View's item (with AJAX) when hovering or clicking it? In my previous question How to mark a Message as &#39;viewed&#39; when a user sees it in a View?, I explained that I'd like to flag a Message when it's hovered or clicked in a View. @Geoff suggested to create an AJAX callback in his answer, but I've no idea how to accomplish that.

How can this be done? Is this the easiest approach?
The entire process may seem a little complicated at first, but it's easy once we break it down into smaller parts and understand how it all comes together. 

Basically we have two parts which we need to address. Firstly the "backend" logic where we will be implementing hook_menu, allowing us to receive an AJAX request via a custom menu route and then flag our Message as seen. Then secondly the "frontend" logic where we'll be implementing a little bit of jQuery to trigger our AJAX calls (using the proper Drupal.behaviours way of course) :)

With this example I'm assuming you have created a Message entity and have added a boolen field to it. We'll use this to store our flag to indicate whether the Message has been "seen" or not. 

Once you've done that, go ahead and create a simple custom module and implement hook_menu using the following example:

/**
* Implements hook_menu().
*/
function my_example_menu() {
  $items['my_example/message/seen/%'] = array(  
  'page callback' =&gt; 'my_example_flag_message',
  'page arguments' =&gt; array(3),
  'access callback' =&gt; 'my_example_message_access',
  'access arguments' =&gt; array(3),
  'type' =&gt; MENU_CALLBACK,
  );
  return $items;
}


Now before we start writing the page callback function which will flag our message as seen, we need to make sure that we implement proper access rights. This ensures the user accessing our custom menu route actually "owns" the message, and isn't some malicious hacker trying to annoy us and mark all the messages on your system as "seen" as some kind of lame prank haha! See below:

/**
 *  Access callback to ensure user has the right to message entity
 */
function my_example_message_access($msg_id) {

  global $user;

  $access = TRUE;

  //if anonymous user then throw access denied
  if(!$user-&gt;uid) {
    return FALSE;
  }

  //load our message entity and check the uid
  $msg = entity_load('message', array($msg_id));

  if($msg[$msg_id]-&gt;uid != $user-&gt;uid) {
    return FALSE;
  }

  return $access;
}


You can test the access callback by visiting http://example.com/my_example/message/seen/[MESSAGE_ID] and trying out different message id's logged in as different users. If a message doesn't belong to you, Drupal should be giving you the old "Access Denied" message.

Now that we know our AJAX route is protected by Drupal access control, we can go ahead and write the page callback function which will flag our Message entity as "seen":

//page callback function
function my_example_flag_message($msg_id){

  $response = array('success' =&gt; FALSE);

  //first check that the message id argument is present
  if(!isset($msg_id) || $msg_id == 0){
    return drupal_json_output($response);
    drupal_exit();
  }

  //load our message entity
  $msg = entity_load('message', array($msg_id));

  //set the flag to TRUE
  $msg[$msg_id]-&gt;field_YOUR_FIELD_MACHINE_NAME[LANGUAGE_NONE][0]['value'] = 1;

  //save our message entity
  if(entity_save('message', $msg[$msg_id])){
    $response['success'] = TRUE;
  }else{
    $response['success'] = FALSE;
  }

  //return the status of our attempt at saving our entity back to the front end
  return drupal_json_output($response);
  drupal_exit();
} 


Great so if you made it this far and didn't fall asleep reading that wall of text, then you should now have a working route which accepts a message id, and marks that message as "seen" (as long as it belongs to you). :)

Then our final piece of the puzzle is attaching a Drupal behaviour to each View row, enabled as to fire an AJAX call to our Drupal route and trigger our backend logic. I'm assuming you know some basic jQuery, but here's the example script you'll need to add to your page using the drupal_add_js() function or something similar. We'll call it my_example.js:

(function ($) {
  Drupal.behaviors.my_example = {
    attach: function(context, settings) {
      //you can adjust this jQuery selector to anything you like
      $('.view-row').click(function(e){
        //I'm assuming the message ID is in view row markup as a data attribe (eg: data-message-id="[MID]")
        var msgID = $(this).data('message-id');
        //trigger our jQuery AJAX call
        $.ajax({
          type: 'POST',
          url: '/my_example/message/seen/' + msgID,
          dataType: 'json',
          data: 'seen=1', //added some arb param here as an example
          beforeSend: function(){
            //if you want to do anything fancy before the AJAX call do it here
          },
          success: function(response){
            //if we successfully updated the message            
            if(response.success == true){           
              //do something fancy like display a message if you like
            }else{
              //if the update failed display an error message
            }
          },
          error: function(jqXHR, textStatus, errorThrown) {
            //if there was some kind of javascript / jquery error you can debug it here
          }
        });
      });
    }
  }
})(jQuery);


And hey presto, we now have some jQuery attaching our Drupal behaviour to each View row which when clicked, will fire off our AJAX trigger and then get Drupal to update your message.

This design pattern opened up a whole host of other ideas (think AngularJS and other exciting geeky tech) for my use of Drupal. I hope it helps you too :)

Obviously if there's anyone else out there with a better implementation please let me know!