1

I'd like to use ajax_command_invoke() to enable jQuery UI Droppable when returning from an AJAX request.

If I run the following command from the JavaScript console, jQuery UI Droppable is properly enabled:

jQuery('.elements-to-make-droppable').droppable({
  drop: function( event, ui ) {
    jQuery( this )
      .addClass( "ui-state-highlight" )
  }
});

However, when I try to return this command from my AJAX callback:

$commands = array();
$commands[] = ajax_command_invoke('.elements-to-make-droppable', 'droppable', array('{
  drop: function( event, ui ) {
    jQuery( this )
      .addClass( "ui-state-highlight" )
  }
}'));
return array('#type' => 'ajax', '#commands' => $commands);

...it doesn't work.

How should I be doing this?

2
  • On the client side, ajax_command_invoke() is using Function.prototype.apply(), whose second argument is the third argument of ajax_command_invoke(). So I guess the question becomes: is there a way to control the way the third argument is serialized, so I can pass my literal JSON object text instead of having it encoded by ajax_command_invoke()?
    – smokris
    Dec 14, 2012 at 17:50
  • Apparently not, since ajax_render() feeds the whole mess to drupal_json_encode().
    – smokris
    Dec 14, 2012 at 17:51

2 Answers 2

2

I solved this by creating a little jQuery Plugin that calls droppable(), and using ajax_command_invoke() to call my plugin.

In the PHP code that builds the page, I added:

drupal_add_js(drupal_get_path('module', 'my_module') . '/my_module.js');

In my_module.js, I added:

jQuery.fn.my_module_make_droppable = function() {
  jQuery(this).droppable({
    drop: function(event, ui) {
      jQuery(this).addClass( "ui-state-highlight" );
    }
  });
}

And my AJAX callback is now:

$commands = array();
$commands[] = ajax_command_invoke('.elements-to-make-droppable', 'my_module_make_droppable');
return array('#type' => 'ajax', '#commands' => $commands);
1

See also: https://drupal.stackexchange.com/a/73738/17676 -- instead of writing new jQuery functions, you can also use events and triggers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.