Using jQuery to communicate to Drupal 7 via AJAX I've been learning how to use AJAX with Drupal 7. I already know how to use the '#ajax' attribute with a form and also how to use the 'use-ajax' class with a link.

I have a nice jQuery slider on my page that emits a jQuery event (called 'slide') every time the slider moves to a new picture. The event also contains which slide number we will be viewing. I can bind to the event using jQuery like this:

$('.slider').bind('slide', function(e, data) { alert(data.slide); });


That will pop up an alert showing the current slide. Instead I want to make an AJAX call using Drupal 7's AJAX and pass this current slide number to Drupal.

I've been searching for an answer and I think it might have something to do with the Drupal.ajax DOM object but I'm not sure.
I am assuming you'd like to display some data when you're moving the slider around.

The way I do it is without using the '#ajax' attribute.

Implement the AJAX call, send the slider value as POST variable to '/foo/ajax':

    jQuery('#slider').slider({
            // Define your slider (min, max etc)
            ...
            // Add event handler
            change: function(event, ui) {
                jQuery.ajax({
                    type: 'POST',
                    url: '/foo/ajax',
                    dataType: 'json',
                    success: ajaxCompleted,
                    // Might want to use 'ui' instead of jQuery('#slider').
                    data: 'slider_value=' + jQuery('#slider').slider('values', 0);
                });
            }
    });


Make a menu item that's called when the slider moves around:

function foo_menu() {
  ...
  $items['foo/ajax'] = array(
    'title' =&gt; t('foo AJAX'),
    'type' =&gt; MENU_CALLBACK,
    'page callback' =&gt; 'foo_ajax',
    'access arguments' =&gt; array('access content'),
  );
  ...
  return $items;
}


Implement the foo_ajax page callback:

function foo_ajax () {
  // Retrieve the slider value
  $slider_value = (int)$_POST['slider_value'];

  // Get some id's from the foo table
  $result = db_query('SELECT id FROM {foo} WHERE value = :value', array(':value' =&gt; $slider_value));
  $data = array();
  foreach ($result as $row) {
    // Do something with data
    // Parse to json

    $data[] = $row-&gt;id;
  }

  // Return json
  drupal_json_output($data)
}


Implement ajaxCompleted (within your javascript):

function ajaxCompleted () {
    // Parse Json
    // Add some stuff to your DOM.
}