I have made a ajax'ed multistep/wizard form using the ctools API. In one of the steps, I have a table being filled dynamically using ajax commands (i.e ctools_ajax_command_before). After each row is created, I want to do the following:
-> Hide/show a row in the table conditionally (based on rowcount)
-> Clear a textfield
-> Set focus on the textfield

I don't see any commands making it possible to invoke javascript functions on objects/selectors. Therefore I have added the following commands:

1) ctools_ajax_command_func($selector, $function_name)
Will execute a function ($function_name) on the selected object ($selector)

2) ctools_ajax_command_eval ($argument)
$argument should contain plain javascript, which will be invoked in the browser using eval().

Please let me know if this functionality already is present in ctools, I was at least not able to find it.

---------------
PHP CODE:
---------------

<?php
function ctools_ajax_command_func($selector, $value) {
   return array(
    
'command' => 'func',
    
'selector' => $selector,
    
'value' => $value,
   );
}
function
ctools_ajax_command_eval($argument) {
   return array(
    
'command' => 'eval',
    
'argument' => $argument,
   );
}
?>

------------
JS-CODE:
------------

Drupal.CTools.AJAX.commands.func = function(data) {
  eval('$("'+data.selector+'")'+data.value);
};

Drupal.CTools.AJAX.commands.eval = function(data) {
  eval(data.argument);
};

---------------------
Example Usage:
---------------------
The following two statements does exactly the same: it will clear the input field matching "input#email" (i.e. the val function will be invoked with empty string):

<?php
ctools_ajax_command_func
('input#email', '.val("")');
ctools_ajax_command_eval('$("input#email").val("")');
?>

Comments

paalj’s picture

Title:Invoking a javascript function using ajax command» Invoking a javascript function using ctools ajax command
stevegmag’s picture

New to using ctools in module development. You have these functions called directly. Can these functions be added to the $commands[] array that gets rendered? Can I pass it a function that's in an included js file. I have the need to process objects after they get swapped with the ctools_ajax_render($commands) function in a module, but this function exits and prevents a direct call. I'm actually surprise that ctools doesn't have this type of functionality built in already (it may, but I haven't seen it either). I'm also getting "Cannot read property 'AJAX' of undefined" error when I add your js code.

stevegmag’s picture

I just added the following to my js file that gets include via the module:

$().ajaxComplete(function(e, xhr, settings) {
    // do my thing here
});

Let me know if there is a better way to do this.