I have a db table with items I need to remove.

On the /user page, I have a list of said items corresponding to the current user.

The user clicks a delete icon and the item disappears.

The script.js file:

$(function() {
  // remove item from display
  $('.gift-list .registry-item .remove').click(function(e) {
    $(this).parent().fadeOut('slow');

    // remove item from db
    // ajax code goes here
  });
});

I have a function in mymodule.module that will include the removal code.

How do I call my function via Ajax, so the page does not reload for the user? How can I make it degrade gracefully?

Thanks

Comments

nevets’s picture

You need a menu item (type = MENU_CALLBACK) in your modules hook_menu() that has as the page callback the function in mymodule.module. Function should generally print something (I generally use the json format) even if its only a success indicator. So your function might end in something like

drupal_json(array('status' => TRUE));

or if you need to return more than success, something like

drupal_json(array('status' => TRUE, 'data' => $output));
HXn’s picture

Worked like a charm.

For those who may come across this post, here is the code I have:

mymodule.module

function registry_menu() {
  $items = array();

  ...

  $items['user/registry-item-remove'] = array(
    'title' => t('registry.'),
    'page callback' => 'registry_item_remove',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
  );

  ...

  return $items;
}

...

function registry_item_remove() {
  global $user;
  
  db_query('DELETE FROM registry WHERE rid=%d', $_GET['rid']);

  $result = db_query('SELECT COUNT(*) as count FROM registry WHERE uid=%d', $user->uid);
  $registry_items = db_fetch_object($result);
  print $registry_items->count;

  exit();
}

script.js

$(function() {
  // remove item from display
  $('.gift-list .registry-item .remove').click(function() {
    $(this).parent().fadeOut('slow');

    // remove item from db

    // callback function for Ajax call
    var callback = function(data) { 
      if (data == 0) {
        $('#gift-list').html('<em>You have no saved gifts.</em>');
        return;
      }
    }

    // call item from hook_menu
    $.get('user/registry-item-remove', 'rid=' + $(this).attr('id'), callback);

    // prevent entire page from reloading
    return false;
  });
});
gmwraj’s picture

Thanks for the solution. It just work nicely.