Problem/Motivation

Drupal.ajax.insert javascript method can only insert returned markup into the page once. An ajax command such as the following:

ajax_command_replace('div.class', '<div class="class">Some Content</div>');

Will replace the first occurrence of div.class but remove all of the others.

Proposed resolution

This behaviour happens because in ajax.js a jQuery object is passed to the insert method, rather than the html. When this happens jQuery prevents the object from being inserted twice, but this is sometimes desired behaviour.

Rather than passing the jQuery object, pass the outerHTML.

Remaining tasks

Write patch.

User interface changes

None.

API changes

None.

Data model changes

None.

Comments

rlmumford created an issue. See original summary.

rlmumford’s picture

Status: Active » Needs work
StatusFileSize
new1.76 KB

This patch allows the replaceWith ajax command to work with multiple elements but breaks all effects because the new_content variable is no longer the object that is actually in the dom tree

rlmumford’s picture

Status: Needs work » Needs review
Issue tags: +jQuery, +DrupalWTF
StatusFileSize
new3.93 KB
new2.59 KB

This patch fixes the effects and behaviours integrations broken by the last patch. The key portion of the patch is the following.

    // Add the new content to the DOM.
    // jQuery will only allow an object to be added to the DOM tree once so,
    // to maintain functionality with behaviours and effects, we explicitly
    // clone and store a copy of new_content for each replacement.
    var new_elements = [];
    wrapper.each(function() {
      var new_element = new_content.clone();
      $(this)[method](new_element);
      new_elements[] = new_element;
    });

I did this this way as although some of the methods return the newly added jQuery objects, replaceWith returns the dom objects that were removed instead. This meant that something like var new_elements = wrapper[method](new_content.prop('outerHTML')); was not going to work with behaviors and effects consistently.

rlmumford’s picture

StatusFileSize
new2.58 KB
new1.78 KB

This patch undoes the white space fixes that should not be included in this patch and makes sure that the new_element gets added to the list of new elements.

Status: Needs review » Closed (outdated)

Automatically closed because Drupal 7 security and bugfix support has ended as of 5 January 2025. If the issue verifiably applies to later versions, please reopen with details and update the version.