I encountered a small problem when using AJAX to load in a textarea with the WYSIWYG (with media plugin). Essentially, the media browser worked fine before the AJAX call but after the AJAX call, it would not submit the form after selecting an already uploading image and would give a Javascript error about the variable src not having a function "replace"

I tracked it down to this line:

defaults.src = defaults.src.replace('-media_id-', mediaFile.fid) + '&fields=' + JSON.stringify(mediaFile.fields);

where defaults comes from this call:

Drupal.media.popups.mediaStyleSelector.getDefaults = function () {
  return {
    src: Drupal.settings.media.styleSelectorUrl,
    onLoad: Drupal.media.popups.mediaStyleSelector.mediaBrowserOnLoad
  };
};

When debugging, the styleSelectorUrl was an array after the AJAX called. I suspect something about applying the same setting twice in the same page is causing them to become arrays instead of strings (not sure if this is a media problem or a core problem in how settings are extended during AJAX requests).

Adding this code fixed my problem:

(function($) {
  
  $(document).ajaxComplete(function() {
    if (typeof Drupal.settings.media.browserUrl === 'object') {
      Drupal.settings.media.browserUrl = Drupal.settings.media.browserUrl[0];
    }
    if (typeof Drupal.settings.media.styleSelectorUrl === 'object') {
      Drupal.settings.media.styleSelectorUrl = Drupal.settings.media.styleSelectorUrl[0];
    }
  });
  
})(jQuery);

But it could be fixed a better way - just not sure if media should check to see if it's an array or not, or if core should extend settings better for AJAX calls.

Comments

lotyrin’s picture

Title: Loading media (via WYSIWYG) through AJAX causes duplicate URLs » Loading media (via WYSIWYG) through AJAX causes duplicate settings values

This happens with all of media's settings in AJAX request with multiple media fields + their attachments.

Or at least when there are both media fields and media WYSIWYG integration.

drupal_add_js() is called twice (or more) with the settings for media, and ajax_render's behavior merges them and gets us arrays instead of values.

lotyrin’s picture

This is not Media's issue. #1983096: Bring JS settings merging in ajax_render() in line with drupal_get_js() is the culprit. ajax_render merges js settings together incorrectly.

lotyrin’s picture

Status: Active » Closed (duplicate)
lotyrin’s picture