Drupal 7 ajax_command_ * creates unwanted div

I populate a select box with an AJAX callback in Drupal 7. I tried both ajax_command_append () and ajax_command_html () to set new statements <option...>

, but both of them wrap the HTML I create internally <div>

. This results in <select>

not displaying any options.

Is there a way to tell Drupal "Hey stupid, this is exactly the HTML I want, not mess with it"?

I can code some jQuery to remove the div I think, but it would be much better if I could prevent it from being added in the first place.

+3


source to share


5 answers


Yes, you can!

Declare your own js call. In the example below, I have used a span instead of a div. But you can obviously remove the wrapper all at once.

PHP:



function my_ajax_callback() {
  $data = 'saved!';
  // instead of using ajax_command_html, we provide our own 
  // js custom callback function
  $output = array(
    '#type' => 'ajax',
    '#commands' => array(
      array('command' => 'myjscallback', 'data' => $data),
    ),
  );

  return $output; 
}

      

JS:

$(function() {
  Drupal.ajax.prototype.commands.myjscallback = function (ajax, response, status) {
    $('#save-btn-message').html('<span>' + response.data + '</span>');
  };
});

      

+4


source


The answer is yes. Just use this instead:



$commands[] = ajax_command_invoke('#mywrapper', 'html', array($output));

      

+2


source


So, it seems like the answer is no (or at least not without a kernel hack and I won't have dead kittens on my conscience).

misc / ajax.js contains the following:

var new_content_wrapped = $('<div></div>').html(response.data);

      

In the comments, it explains why they require the first HTML element to be the top level. If so, no wrapper <div>

is used. In my case, I am replacing items <option>

, so I get <div>

.

Now I could just replace the whole one <select>

, but that causes other problems in my case due to scripts that style things on page load. Instead of finding them and restarting them, it seems to be easier to just ajax_command_invoke a script to run after my parameters have loaded to remove the div wrapper.

EDIT: As a workaround, I found what I can do ajax_command_invoke($selector, 'html', array('<option...>'));

and it bypasses the div adding code. Kinda is sneaky but it works ...

+1


source


you can use on this link http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#ajax

for more reference and example download this module http://drupal.org/project/examples it has all the custom code examples and "ajax_example" as well

0


source


It works for me!

    $ selector = '# my-select';
    $ method = 'append';
    $ opts = array ('new option');

    $ commands [] = ajax_command_invoke ($ selector, $ method, $ opts);

    return array ('# type' => 'ajax', '#commands' => $ commands);
-1


source