diff --git a/core/core.services.yml b/core/core.services.yml
index 589c5f6..6948cd6 100644
--- a/core/core.services.yml
+++ b/core/core.services.yml
@@ -815,6 +815,11 @@ services:
     class: Drupal\Core\EventSubscriber\AjaxSubscriber
     tags:
       - { name: event_subscriber }
+  form_ajax_subscriber:
+    class: Drupal\Core\Form\EventSubscriber\FormAjaxSubscriber
+    arguments: ['@form_ajax_response_builder']
+    tags:
+      - { name: event_subscriber }
   route_enhancer.lazy_collector:
     class: Drupal\Core\Routing\LazyRouteEnhancer
     tags:
@@ -885,6 +890,9 @@ services:
   controller.entity_form:
     class: Drupal\Core\Entity\HtmlEntityFormController
     arguments: ['@controller_resolver', '@form_builder', '@entity.manager']
+  form_ajax_response_builder:
+    class: Drupal\Core\Form\FormAjaxResponseBuilder
+    arguments: ['@main_content_renderer.ajax', '@current_route_match']
   router_listener:
     class: Symfony\Component\HttpKernel\EventListener\RouterListener
     tags:
diff --git a/core/lib/Drupal/Component/Utility/Html.php b/core/lib/Drupal/Component/Utility/Html.php
index 60b83df..b6eb649 100644
--- a/core/lib/Drupal/Component/Utility/Html.php
+++ b/core/lib/Drupal/Component/Utility/Html.php
@@ -35,11 +35,11 @@ class Html {
   protected static $seenIds;
 
   /**
-   * Contains the current AJAX HTML IDs.
+   * Stores whether the current request was sent via AJAX.
    *
-   * @var string
+   * @var bool
    */
-  protected static $ajaxHTMLIDs;
+  protected static $isAjax = FALSE;
 
   /**
    * Prepares a string for use as a valid class name.
@@ -102,13 +102,13 @@ public static function cleanCssIdentifier($identifier, array $filter = array(
   }
 
   /**
-   * Sets the AJAX HTML IDs.
+   * Sets if this request is an Ajax request.
    *
-   * @param string $ajax_html_ids
-   *   The AJAX HTML IDs, probably coming from the current request.
+   * @param bool $is_ajax
+   *   TRUE if this request is an Ajax request, FALSE otherwise.
    */
-  public static function setAjaxHtmlIds($ajax_html_ids = '') {
-    static::$ajaxHTMLIDs = $ajax_html_ids;
+  public static function setIsAjax($is_ajax) {
+    static::$isAjax = $is_ajax;
   }
 
   /**
@@ -142,43 +142,15 @@ public static function setAjaxHtmlIds($ajax_html_ids = '') {
   public static function getUniqueId($id) {
     // If this is an Ajax request, then content returned by this page request
     // will be merged with content already on the base page. The HTML IDs must
-    // be unique for the fully merged content. Therefore, initialize $seen_ids
-    // to take into account IDs that are already in use on the base page.
+    // be unique for the fully merged content. Therefore use unique IDs.
+    if (static::$isAjax) {
+      return static::getId($id) . '--' . Crypt::randomBytesBase64(8);
+    }
+
+    // @todo Remove all that code once we switch over to random IDs only,
+    // see https://www.drupal.org/node/1090592.
     if (!isset(static::$seenIdsInit)) {
-      // Ideally, Drupal would provide an API to persist state information about
-      // prior page requests in the database, and we'd be able to add this
-      // function's $seen_ids static variable to that state information in order
-      // to have it properly initialized for this page request. However, no such
-      // page state API exists, so instead, ajax.js adds all of the in-use HTML
-      // IDs to the POST data of Ajax submissions. Direct use of $_POST is
-      // normally not recommended as it could open up security risks, but
-      // because the raw POST data is cast to a number before being returned by
-      // this function, this usage is safe.
-      if (empty(static::$ajaxHTMLIDs)) {
-        static::$seenIdsInit = array();
-      }
-      else {
-        // This function ensures uniqueness by appending a counter to the base
-        // id requested by the calling function after the first occurrence of
-        // that requested id. $_POST['ajax_html_ids'] contains the ids as they
-        // were returned by this function, potentially with the appended
-        // counter, so we parse that to reconstruct the $seen_ids array.
-        $ajax_html_ids = explode(' ', static::$ajaxHTMLIDs);
-        foreach ($ajax_html_ids as $seen_id) {
-          // We rely on '--' being used solely for separating a base id from the
-          // counter, which this function ensures when returning an id.
-          $parts = explode('--', $seen_id, 2);
-          if (!empty($parts[1]) && is_numeric($parts[1])) {
-            list($seen_id, $i) = $parts;
-          }
-          else {
-            $i = 1;
-          }
-          if (!isset(static::$seenIdsInit[$seen_id]) || ($i > static::$seenIdsInit[$seen_id])) {
-            static::$seenIdsInit[$seen_id] = $i;
-          }
-        }
-      }
+      static::$seenIdsInit = array();
     }
     if (!isset(static::$seenIds)) {
       static::$seenIds = static::$seenIdsInit;
diff --git a/core/lib/Drupal/Core/EventSubscriber/AjaxSubscriber.php b/core/lib/Drupal/Core/EventSubscriber/AjaxSubscriber.php
index 8996b5d..8a85659 100644
--- a/core/lib/Drupal/Core/EventSubscriber/AjaxSubscriber.php
+++ b/core/lib/Drupal/Core/EventSubscriber/AjaxSubscriber.php
@@ -20,13 +20,21 @@
 class AjaxSubscriber implements EventSubscriberInterface {
 
   /**
-   * Sets the AJAX HTML IDs from the current request.
+   * Request parameter to indicate that a request is a Drupal Ajax request.
+   */
+  const AJAX_REQUEST_PARAMETER = '_drupal_ajax';
+
+  /**
+   * Sets the AJAX parameter from the current request.
    *
    * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
    *   The response event, which contains the current request.
    */
   public function onRequest(GetResponseEvent $event) {
-    Html::setAjaxHtmlIds($event->getRequest()->request->get('ajax_html_ids', ''));
+    // Pass to the Html class that the current request is an Ajax request.
+    if ($event->getRequest()->request->get(static::AJAX_REQUEST_PARAMETER)) {
+      Html::setIsAjax(TRUE);
+    }
   }
 
   /**
diff --git a/core/lib/Drupal/Core/Form/EventSubscriber/FormAjaxSubscriber.php b/core/lib/Drupal/Core/Form/EventSubscriber/FormAjaxSubscriber.php
new file mode 100644
index 0000000..ffbd8f3
--- /dev/null
+++ b/core/lib/Drupal/Core/Form/EventSubscriber/FormAjaxSubscriber.php
@@ -0,0 +1,102 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\Core\Form\EventSubscriber\FormAjaxSubscriber.
+ */
+
+namespace Drupal\Core\Form\EventSubscriber;
+
+use Drupal\Core\Form\FormAjaxException;
+use Drupal\Core\Form\FormAjaxResponseBuilderInterface;
+use Symfony\Component\EventDispatcher\EventSubscriberInterface;
+use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
+use Symfony\Component\HttpKernel\KernelEvents;
+
+/**
+ * Wraps AJAX form submissions that are triggered via an exception.
+ */
+class FormAjaxSubscriber implements EventSubscriberInterface {
+
+  /**
+   * The form AJAX response builder.
+   *
+   * @var \Drupal\Core\Form\FormAjaxResponseBuilderInterface
+   */
+  protected $formAjaxResponseBuilder;
+
+  /**
+   * Constructs a new FormAjaxSubscriber.
+   *
+   * @param \Drupal\Core\Form\FormAjaxResponseBuilderInterface $form_ajax_response_builder
+   *   The form AJAX response builder.
+   */
+  public function __construct(FormAjaxResponseBuilderInterface $form_ajax_response_builder) {
+    $this->formAjaxResponseBuilder = $form_ajax_response_builder;
+  }
+
+  /**
+   * Catches a form AJAX exception and build a response from it.
+   *
+   * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
+   *   The event to process.
+   */
+  public function onException(GetResponseForExceptionEvent $event) {
+    // Extract the form AJAX exception (it may have been passed to another
+    // exception before reaching here).
+    if ($exception = $this->getFormAjaxException($event->getException())) {
+      $request = $event->getRequest();
+      $form = $exception->getForm();
+      $form_state = $exception->getFormState();
+
+      // Set the build ID from the request as the old build ID on the form.
+      $form['#build_id_old'] = $request->get('form_build_id');
+
+      try {
+        $response = $this->formAjaxResponseBuilder->buildResponse($request, $form, $form_state, []);
+
+        // Since this response is being set in place of an exception, explicitly
+        // mark this as a 200 status.
+        $response->headers->set('X-Status-Code', 200);
+        $event->setResponse($response);
+      }
+      catch (\Exception $e) {
+        // Otherwise, replace the existing exception with the new one.
+        $event->setException($e);
+      }
+    }
+  }
+
+  /**
+   * Extracts a form AJAX exception.
+   *
+   * @param \Exception $e
+   *  A generic exception that might contain a form AJAX exception.
+   *
+   * @return \Drupal\Core\Form\FormAjaxException|null
+   *   Either the form AJAX exception, or NULL if none could be found.
+   */
+  protected function getFormAjaxException(\Exception $e) {
+    $exception = NULL;
+    while ($e) {
+      if ($e instanceof FormAjaxException) {
+        $exception = $e;
+        break;
+      }
+
+      $e = $e->getPrevious();
+    }
+    return $exception;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function getSubscribedEvents() {
+    // Run before exception.logger.
+    $events[KernelEvents::EXCEPTION] = ['onException', 51];
+
+    return $events;
+  }
+
+}
diff --git a/core/lib/Drupal/Core/Form/FormAjaxException.php b/core/lib/Drupal/Core/Form/FormAjaxException.php
new file mode 100644
index 0000000..e9062bb
--- /dev/null
+++ b/core/lib/Drupal/Core/Form/FormAjaxException.php
@@ -0,0 +1,69 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\Core\Form\FormAjaxException.
+ */
+
+namespace Drupal\Core\Form;
+
+/**
+ * Custom exception to break out of AJAX form processing.
+ */
+class FormAjaxException extends \Exception {
+
+  /**
+   * The form definition.
+   *
+   * @var array
+   */
+  protected $form;
+
+  /**
+   * The form state.
+   *
+   * @var \Drupal\Core\Form\FormStateInterface
+   */
+  protected $formState;
+
+  /**
+   * Constructs a FormAjaxException object.
+   *
+   * @param array $form
+   *   The form definition.
+   * @param \Drupal\Core\Form\FormStateInterface $form_state
+   *   The form state.
+   * @param string $message
+   *   (optional) The exception message.
+   * @param int $code
+   *   (optional) A user defined exception code.
+   * @param \Exception $previous
+   *   (optional) The previous exception for nested exceptions.
+   */
+  public function __construct(array $form, FormStateInterface $form_state, $message = "", $code = 0, \Exception $previous = NULL) {
+    parent::__construct($message, $code, $previous);
+    $this->form = $form;
+    $this->formState = $form_state;
+  }
+
+  /**
+   * Gets the form definition.
+   *
+   * @return array
+   *   The form structure.
+   */
+  public function getForm() {
+    return $this->form;
+  }
+
+  /**
+   * Gets the form state.
+   *
+   * @return \Drupal\Core\Form\FormStateInterface
+   *   The current state of the form.
+   */
+  public function getFormState() {
+    return $this->formState;
+  }
+
+}
diff --git a/core/lib/Drupal/Core/Form/FormAjaxResponseBuilder.php b/core/lib/Drupal/Core/Form/FormAjaxResponseBuilder.php
new file mode 100644
index 0000000..4b826ff
--- /dev/null
+++ b/core/lib/Drupal/Core/Form/FormAjaxResponseBuilder.php
@@ -0,0 +1,95 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\Core\Form\FormAjaxResponseBuilder.
+ */
+
+namespace Drupal\Core\Form;
+
+use Drupal\Core\Ajax\AjaxResponse;
+use Drupal\Core\Ajax\UpdateBuildIdCommand;
+use Drupal\Core\Render\MainContent\MainContentRendererInterface;
+use Drupal\Core\Routing\RouteMatchInterface;
+use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\HttpKernel\Exception\HttpException;
+
+/**
+ * Builds an AJAX form response.
+ *
+ * Given the current request, a form render array, its form state, and any AJAX
+ * commands to apply to the form, build a response object.
+ */
+class FormAjaxResponseBuilder implements FormAjaxResponseBuilderInterface {
+
+  /**
+   * The main content to AJAX Response renderer.
+   *
+   * @var \Drupal\Core\Render\MainContent\MainContentRendererInterface
+   */
+  protected $ajaxRenderer;
+
+  /**
+   * The current route match.
+   *
+   * @var \Drupal\Core\Routing\RouteMatchInterface
+   */
+  protected $routeMatch;
+
+  /**
+   * Constructs a new FormAjaxResponseBuilder.
+   *
+   * @param \Drupal\Core\Render\MainContent\MainContentRendererInterface $ajax_renderer
+   *   The ajax renderer.
+   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
+   *   The current route match.
+   */
+  public function __construct(MainContentRendererInterface $ajax_renderer, RouteMatchInterface $route_match) {
+    $this->ajaxRenderer = $ajax_renderer;
+    $this->routeMatch = $route_match;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function buildResponse(Request $request, array $form, FormStateInterface $form_state, array $commands) {
+    // If the form build ID has changed, issue an Ajax command to update it.
+    if (isset($form['#build_id_old']) && $form['#build_id_old'] !== $form['#build_id']) {
+      $commands[] = new UpdateBuildIdCommand($form['#build_id_old'], $form['#build_id']);
+    }
+
+    // We need to return the part of the form (or some other content) that needs
+    // to be re-rendered so the browser can update the page with changed
+    // content. Since this is the generic menu callback used by many Ajax
+    // elements, it is up to the #ajax['callback'] function of the element (may
+    // or may not be a button) that triggered the Ajax request to determine what
+    // needs to be rendered.
+    $callback = NULL;
+    if (($triggering_element = $form_state->getTriggeringElement()) && isset($triggering_element['#ajax']['callback'])) {
+      $callback = $triggering_element['#ajax']['callback'];
+    }
+    $callback = $form_state->prepareCallback($callback);
+    if (empty($callback) || !is_callable($callback)) {
+      throw new HttpException(500, 'The specified #ajax callback is empty or not callable.');
+    }
+    $result = call_user_func_array($callback, [&$form, &$form_state]);
+
+    // If the callback is an #ajax callback, the result is a render array, and
+    // we need to turn it into an AJAX response, so that we can add any commands
+    // we got earlier; typically the UpdateBuildIdCommand when handling an AJAX
+    // submit from a cached page.
+    if ($result instanceof AjaxResponse) {
+      $response = $result;
+    }
+    else {
+      /** @var \Drupal\Core\Ajax\AjaxResponse $response */
+      $response = $this->ajaxRenderer->renderResponse($result, $request, $this->routeMatch);
+    }
+
+    foreach ($commands as $command) {
+      $response->addCommand($command, TRUE);
+    }
+    return $response;
+  }
+
+}
diff --git a/core/lib/Drupal/Core/Form/FormAjaxResponseBuilderInterface.php b/core/lib/Drupal/Core/Form/FormAjaxResponseBuilderInterface.php
new file mode 100644
index 0000000..720ecc8
--- /dev/null
+++ b/core/lib/Drupal/Core/Form/FormAjaxResponseBuilderInterface.php
@@ -0,0 +1,37 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\Core\Form\FormAjaxResponseBuilderInterface.
+ */
+
+namespace Drupal\Core\Form;
+
+use Symfony\Component\HttpFoundation\Request;
+
+/**
+ * Provides an interface for building AJAX form responses.
+ */
+interface FormAjaxResponseBuilderInterface {
+
+  /**
+   * Builds a response for an AJAX form.
+   *
+   * @param \Symfony\Component\HttpFoundation\Request $request
+   *   The current request.
+   * @param array $form
+   *   An associative array containing the structure of the form.
+   * @param \Drupal\Core\Form\FormStateInterface $form_state
+   *   The current state of the form.
+   * @param array $commands
+   *   An array of AJAX commands to apply to the form.
+   *
+   * @return \Drupal\Core\Ajax\AjaxResponse
+   *   An AJAX response representing the form and its AJAX commands.
+   *
+   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
+   *   Thrown if the AJAX callback is not a callable.
+   */
+  public function buildResponse(Request $request, array $form, FormStateInterface $form_state, array $commands);
+
+}
diff --git a/core/lib/Drupal/Core/Form/FormBuilder.php b/core/lib/Drupal/Core/Form/FormBuilder.php
index 4b995c1..6be20d1 100644
--- a/core/lib/Drupal/Core/Form/FormBuilder.php
+++ b/core/lib/Drupal/Core/Form/FormBuilder.php
@@ -244,6 +244,12 @@ public function buildForm($form_id, FormStateInterface &$form_state) {
       }
     }
 
+    // If this form is an AJAX request, disable all form redirects.
+    $request = $this->requestStack->getCurrentRequest();
+    if ($ajax_form_request = $request->query->has(static::AJAX_FORM_REQUEST)) {
+      $form_state->disableRedirect();
+    }
+
     // Now that we have a constructed form, process it. This is where:
     // - Element #process functions get called to further refine $form.
     // - User input, if any, gets incorporated in the #value property of the
@@ -257,6 +263,17 @@ public function buildForm($form_id, FormStateInterface &$form_state) {
     // can use it to know or update information about the state of the form.
     $response = $this->processForm($form_id, $form, $form_state);
 
+    // After processing the form, if this is an AJAX form request, interrupt
+    // form rendering and return by throwing an exception that contains the
+    // processed form and form state. This exception will be caught by
+    // \Drupal\Core\Form\EventSubscriber\FormAjaxSubscriber::onException() and
+    // then passed through
+    // \Drupal\Core\Form\FormAjaxResponseBuilderInterface::buildResponse() to
+    // build a proper AJAX response.
+    if ($ajax_form_request && $form_state->isProcessingInput()) {
+      throw new FormAjaxException($form, $form_state);
+    }
+
     // If the form returns a response, skip subsequent page construction by
     // throwing an exception.
     // @see Drupal\Core\EventSubscriber\EnforcedFormResponseSubscriber
@@ -629,6 +646,9 @@ public function prepareForm($form_id, &$form, FormStateInterface &$form_state) {
     }
     if (!isset($form['#id'])) {
       $form['#id'] = Html::getUniqueId($form_id);
+      // Provide a selector usable by JavaScript. As the ID is unique, its not
+      // possible to rely on it in JavaScript.
+      $form['#attributes']['data-drupal-selector'] = Html::getId($form_id);
     }
 
     $form += $this->elementInfo->getInfo('form');
@@ -746,7 +766,16 @@ public function doBuildForm($form_id, &$element, FormStateInterface &$form_state
     }
 
     if (!isset($element['#id'])) {
-      $element['#id'] = Html::getUniqueId('edit-' . implode('-', $element['#parents']));
+      $unprocessed_id = 'edit-' . implode('-', $element['#parents']);
+      $element['#id'] = Html::getUniqueId($unprocessed_id);
+      // Provide a selector usable by JavaScript. As the ID is unique, its not
+      // possible to rely on it in JavaScript.
+      $element['#attributes']['data-drupal-selector'] = Html::getId($unprocessed_id);
+    }
+    else {
+      // Provide a selector usable by JavaScript. As the ID is unique, its not
+      // possible to rely on it in JavaScript.
+      $element['#attributes']['data-drupal-selector'] = Html::getId($element['#id']);
     }
 
     // Add the aria-describedby attribute to associate the form control with its
diff --git a/core/lib/Drupal/Core/Form/FormBuilderInterface.php b/core/lib/Drupal/Core/Form/FormBuilderInterface.php
index 5f8b452..125199d 100644
--- a/core/lib/Drupal/Core/Form/FormBuilderInterface.php
+++ b/core/lib/Drupal/Core/Form/FormBuilderInterface.php
@@ -13,6 +13,11 @@
 interface FormBuilderInterface {
 
   /**
+   * Request key for a form that was triggered via AJAX.
+   */
+  const AJAX_FORM_REQUEST = 'ajax_form';
+
+  /**
    * Determines the ID of a form.
    *
    * @param \Drupal\Core\Form\FormInterface|string $form_arg
@@ -69,6 +74,14 @@ public function getForm($form_arg);
    *   The rendered form. This function may also perform a redirect and hence
    *   may not return at all depending upon the $form_state flags that were set.
    *
+   * @throws \Drupal\Core\Form\FormAjaxException
+   *   Thrown when a form is triggered via an AJAX submission. It will be
+   *   handled by \Drupal\Core\Form\EventSubscriber\FormAjaxSubscriber.
+   * @throws \Drupal\Core\Form\EnforcedResponseException
+   *   Thrown when a form builder returns a response directly, usually a
+   *   \Symfony\Component\HttpFoundation\RedirectResponse. It will be handled by
+   *   \Drupal\Core\EventSubscriber\EnforcedFormResponseSubscriber.
+   *
    * @see self::redirectForm()
    */
   public function buildForm($form_id, FormStateInterface &$form_state);
diff --git a/core/lib/Drupal/Core/Render/Element/RenderElement.php b/core/lib/Drupal/Core/Render/Element/RenderElement.php
index c886fec..73b4c36 100644
--- a/core/lib/Drupal/Core/Render/Element/RenderElement.php
+++ b/core/lib/Drupal/Core/Render/Element/RenderElement.php
@@ -7,6 +7,8 @@
 
 namespace Drupal\Core\Render\Element;
 
+use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
+use Drupal\Core\Form\FormBuilderInterface;
 use Drupal\Core\Form\FormStateInterface;
 use Drupal\Core\Plugin\PluginBase;
 use Drupal\Core\Render\Element;
@@ -127,11 +129,10 @@ public static function preRenderGroup($element) {
    * @see self::preRenderAjaxForm()
    */
   public static function processAjaxForm(&$element, FormStateInterface $form_state, &$complete_form) {
-    $element = static::preRenderAjaxForm($element);
-    if (!empty($element['#ajax_processed'])) {
+    if (!empty($element['#ajax']['url'])) {
       $form_state->setCached();
     }
-    return $element;
+    return static::preRenderAjaxForm($element);
   }
 
   /**
@@ -237,8 +238,14 @@ public static function preRenderAjaxForm($element) {
       // One such substantial difference is form elements that use
       // #ajax['callback'] for determining which part of the form needs
       // re-rendering. For that, we have a special 'system/ajax' route.
+      if (isset($settings['callback']) && !isset($settings['url'])) {
+        $settings['url'] = Url::fromRoute('<current>');
+        $settings['options']['query'][FormBuilderInterface::AJAX_FORM_REQUEST] = TRUE;
+        // Specify that we expect HTML back, despite the AJAX request.
+        $settings['options']['query'][MainContentViewSubscriber::WRAPPER_FORMAT] = 'html';
+      }
       $settings += array(
-        'url' => isset($settings['callback']) ? Url::fromRoute('system.ajax') : NULL,
+        'url' => NULL,
         'options' => array(),
         'dialogType' => 'ajax',
       );
diff --git a/core/misc/ajax.js b/core/misc/ajax.js
index 3cb1c8d..2b9aea3 100644
--- a/core/misc/ajax.js
+++ b/core/misc/ajax.js
@@ -456,6 +456,13 @@ else if (this.element && element.form) {
   Drupal.ajax.WRAPPER_FORMAT = '_wrapper_format';
 
   /**
+   * Request parameter to indicate that a request is a Drupal Ajax request.
+   *
+   * @const
+   */
+  Drupal.Ajax.AJAX_REQUEST_PARAMETER = '_drupal_ajax';
+
+  /**
    * Execute the ajax request.
    *
    * Allows developers to execute an Ajax request manually without specifying
@@ -580,16 +587,8 @@ else if (this.element && element.form) {
       Drupal.detachBehaviors(this.$form.get(0), settings, 'serialize');
     }
 
-    // Prevent duplicate HTML ids in the returned markup.
-    // @see \Drupal\Component\Utility\Html::getUniqueId()
-    var ids = document.querySelectorAll('[id]');
-    var ajaxHtmlIds = [];
-    var il = ids.length;
-    for (var i = 0; i < il; i++) {
-      ajaxHtmlIds.push(ids[i].id);
-    }
-    // Join IDs to minimize request size.
-    options.data.ajax_html_ids = ajaxHtmlIds.join(' ');
+    // Inform Drupal that this is an AJAX request.
+    options.data[Drupal.Ajax.AJAX_REQUEST_PARAMETER] = 1;
 
     // Allow Drupal to return new JavaScript and CSS files to load without
     // returning the ones already loaded.
diff --git a/core/modules/block/js/block.admin.js b/core/modules/block/js/block.admin.js
index b399dd0..23109f4 100644
--- a/core/modules/block/js/block.admin.js
+++ b/core/modules/block/js/block.admin.js
@@ -92,7 +92,7 @@ function showBlockEntry(index, block) {
   Drupal.behaviors.blockHighlightPlacement = {
     attach: function (context, settings) {
       if (settings.blockPlacement) {
-        $('#blocks').once('block-highlight').each(function () {
+        $(context).find('[data-drupal-selector="edit-blocks"]').once('block-highlight').each(function () {
           var $container = $(this);
           // Just scrolling the document.body will not work in Firefox. The html
           // element is needed as well.
diff --git a/core/modules/block/js/block.js b/core/modules/block/js/block.js
index e5c0907..acf7e4a 100644
--- a/core/modules/block/js/block.js
+++ b/core/modules/block/js/block.js
@@ -34,9 +34,9 @@ function checkboxesSummary(context) {
         return vals.join(', ');
       }
 
-      $('#edit-visibility-node-type, #edit-visibility-language, #edit-visibility-user-role').drupalSetSummary(checkboxesSummary);
+      $('[data-drupal-selector="edit-visibility-node-type"], [data-drupal-selector="edit-visibility-language"], [data-drupal-selector="edit-visibility-user-role"]').drupalSetSummary(checkboxesSummary);
 
-      $('#edit-visibility-request-path').drupalSetSummary(function (context) {
+      $('[data-drupal-selector="edit-visibility-request-path"]').drupalSetSummary(function (context) {
         var $pages = $(context).find('textarea[name="visibility[request_path][pages]"]');
         if (!$pages.val()) {
           return Drupal.t('Not restricted');
diff --git a/core/modules/ckeditor/js/ckeditor.drupalimage.admin.js b/core/modules/ckeditor/js/ckeditor.drupalimage.admin.js
index 96288cf..a4ebce2 100644
--- a/core/modules/ckeditor/js/ckeditor.drupalimage.admin.js
+++ b/core/modules/ckeditor/js/ckeditor.drupalimage.admin.js
@@ -14,7 +14,7 @@
    */
   Drupal.behaviors.ckeditorDrupalImageSettingsSummary = {
     attach: function () {
-      $('#edit-editor-settings-plugins-drupalimage').drupalSetSummary(function (context) {
+      $('[data-ckeditor-plugin-id="drupalimage"]').drupalSetSummary(function (context) {
         var root = 'input[name="editor[settings][plugins][drupalimage][image_upload]';
         var $status = $(root + '[status]"]');
         var $maxFileSize = $(root + '[max_size]"]');
diff --git a/core/modules/ckeditor/js/ckeditor.stylescombo.admin.js b/core/modules/ckeditor/js/ckeditor.stylescombo.admin.js
index b73d1b1..76e7421 100644
--- a/core/modules/ckeditor/js/ckeditor.stylescombo.admin.js
+++ b/core/modules/ckeditor/js/ckeditor.stylescombo.admin.js
@@ -33,7 +33,7 @@
       var that = this;
       $context.find('[name="editor[settings][plugins][stylescombo][styles]"]')
         .on('blur.ckeditorStylesComboSettings', function () {
-          var styles = $.trim($('#edit-editor-settings-plugins-stylescombo-styles').val());
+          var styles = $.trim($(this).val());
           var stylesSet = that._generateStylesSetSetting(styles);
           if (!_.isEqual(previousStylesSet, stylesSet)) {
             previousStylesSet = stylesSet;
@@ -105,8 +105,8 @@
    */
   Drupal.behaviors.ckeditorStylesComboSettingsSummary = {
     attach: function () {
-      $('#edit-editor-settings-plugins-stylescombo').drupalSetSummary(function (context) {
-        var styles = $.trim($('#edit-editor-settings-plugins-stylescombo-styles').val());
+      $('[data-ckeditor-plugin-id="stylescombo"]').drupalSetSummary(function (context) {
+        var styles = $.trim($('[data-drupal-selector="edit-editor-settings-plugins-stylescombo-styles"]').val());
         if (styles.length === 0) {
           return Drupal.t('No styles configured');
         }
diff --git a/core/modules/field/src/Tests/Boolean/BooleanFieldTest.php b/core/modules/field/src/Tests/Boolean/BooleanFieldTest.php
index 28f6334..647180c 100644
--- a/core/modules/field/src/Tests/Boolean/BooleanFieldTest.php
+++ b/core/modules/field/src/Tests/Boolean/BooleanFieldTest.php
@@ -171,7 +171,7 @@ function testBooleanField() {
       t('Display setting checkbox is available')
     );
     $this->assertFieldByXPath(
-      '*//input[@id="edit-fields-' . $field_name . '-settings-edit-form-settings-display-label" and @value="1"]',
+      '*//input[starts-with(@id, "edit-fields-' . $field_name . '-settings-edit-form-settings-display-label") and @value="1"]',
       TRUE,
       t('Display label changes label of the checkbox')
     );
diff --git a/core/modules/field/src/Tests/FormTest.php b/core/modules/field/src/Tests/FormTest.php
index 564e300..afa2987 100644
--- a/core/modules/field/src/Tests/FormTest.php
+++ b/core/modules/field/src/Tests/FormTest.php
@@ -435,7 +435,7 @@ function testFieldFormJSAddMore() {
     // Press 'add more' button through Ajax, and place the expected HTML result
     // as the tested content.
     $commands = $this->drupalPostAjaxForm(NULL, $edit, $field_name . '_add_more');
-    $this->setRawContent($commands[1]['data']);
+    $this->setRawContent($commands[2]['data']);
 
     for ($delta = 0; $delta <= $delta_range; $delta++) {
       $this->assertFieldByName("{$field_name}[$delta][value]", $values[$delta], "Widget $delta is displayed and has the right value");
diff --git a/core/modules/field_ui/field_ui.js b/core/modules/field_ui/field_ui.js
index 3c9e5ae..f73df41 100644
--- a/core/modules/field_ui/field_ui.js
+++ b/core/modules/field_ui/field_ui.js
@@ -12,7 +12,7 @@
    */
   Drupal.behaviors.fieldUIFieldStorageAddForm = {
     attach: function (context) {
-      var $form = $(context).find('#field-ui-field-storage-add-form').once('field_ui_add');
+      var $form = $(context).find('[data-drupal-selector="field-ui-field-storage-add-form"]').once('field_ui_add');
       if ($form.length) {
         // Add a few 'form-required' css classes here. We can not use the Form
         // API '#required' property because both label elements for "add new"
@@ -214,7 +214,7 @@ else if ($this.is('.region-empty')) {
 
         // Fire the Ajax update.
         $('input[name=refresh_rows]').val(rowNames.join(' '));
-        $('input#edit-refresh').trigger('mousedown');
+        $('input[data-drupal-selector="edit-refresh"]').trigger('mousedown');
 
         // Disabled elements do not appear in POST ajax data, so we mark the
         // elements disabled only after firing the request.
diff --git a/core/modules/file/src/Controller/FileWidgetAjaxController.php b/core/modules/file/src/Controller/FileWidgetAjaxController.php
index 90176f8..6cc1391 100644
--- a/core/modules/file/src/Controller/FileWidgetAjaxController.php
+++ b/core/modules/file/src/Controller/FileWidgetAjaxController.php
@@ -10,7 +10,12 @@
 use Drupal\Component\Utility\NestedArray;
 use Drupal\Core\Ajax\AjaxResponse;
 use Drupal\Core\Ajax\ReplaceCommand;
+use Drupal\Core\Form\FormAjaxResponseBuilderInterface;
+use Drupal\Core\Form\FormBuilderInterface;
+use Drupal\Core\Render\RendererInterface;
 use Drupal\system\Controller\FormAjaxController;
+use Psr\Log\LoggerInterface;
+use Symfony\Component\DependencyInjection\ContainerInterface;
 use Symfony\Component\HttpFoundation\JsonResponse;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
@@ -21,6 +26,42 @@
 class FileWidgetAjaxController extends FormAjaxController {
 
   /**
+   * The renderer.
+   *
+   * @var \Drupal\Core\Render\RendererInterface
+   */
+  protected $renderer;
+
+  /**
+   * Constructs a FileWidgetAjaxController object.
+   *
+   * @param \Psr\Log\LoggerInterface $logger
+   *   A logger instance.
+   * @param \Drupal\Core\Form\FormBuilderInterface $form_builder
+   *   The form builder.
+   * @param \Drupal\Core\Form\FormAjaxResponseBuilderInterface $form_ajax_response_builder
+   *   The form AJAX response builder.
+   * @param \Drupal\Core\Render\RendererInterface $renderer
+   *   The renderer.
+   */
+  public function __construct(LoggerInterface $logger, FormBuilderInterface $form_builder, FormAjaxResponseBuilderInterface $form_ajax_response_builder, RendererInterface $renderer) {
+    parent::__construct($logger, $form_builder, $form_ajax_response_builder);
+    $this->renderer = $renderer;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function create(ContainerInterface $container) {
+    return new static(
+      $container->get('logger.factory')->get('ajax'),
+      $container->get('form_builder'),
+      $container->get('form_ajax_response_builder'),
+      $container->get('renderer')
+    );
+  }
+
+  /**
    * Processes AJAX file uploads and deletions.
    *
    * @param \Symfony\Component\HttpFoundation\Request $request
diff --git a/core/modules/file/src/Element/ManagedFile.php b/core/modules/file/src/Element/ManagedFile.php
index 40d0c31..7f2bf59 100644
--- a/core/modules/file/src/Element/ManagedFile.php
+++ b/core/modules/file/src/Element/ManagedFile.php
@@ -7,6 +7,7 @@
 
 namespace Drupal\file\Element;
 
+use Drupal\Component\Utility\Html;
 use Drupal\Core\Form\FormStateInterface;
 use Drupal\Core\Render\Element\FormElement;
 use Drupal\Core\Url;
@@ -130,9 +131,6 @@ public static function valueCallback(&$element, $input, FormStateInterface $form
    * support for a default value.
    */
   public static function processManagedFile(&$element, FormStateInterface $form_state, &$complete_form) {
-    // Append the '-upload' to the #id so the field label's 'for' attribute
-    // corresponds with the file element.
-    $element['#id'] .= '-upload';
 
     // This is used sometimes so let's implode it just once.
     $parents_prefix = implode('_', $element['#parents']);
@@ -144,7 +142,11 @@ public static function processManagedFile(&$element, FormStateInterface $form_st
     $element['#files'] = !empty($fids) ? File::loadMultiple($fids) : FALSE;
     $element['#tree'] = TRUE;
 
+    // Generate a unique wrapper HTML ID.
+    $ajax_wrapper_id = Html::getUniqueId('ajax-wrapper');
+
     $ajax_settings = [
+      // @todo Remove this in https://www.drupal.org/node/2500527.
       'url' => Url::fromRoute('file.ajax_upload'),
       'options' => [
         'query' => [
@@ -152,7 +154,7 @@ public static function processManagedFile(&$element, FormStateInterface $form_st
           'form_build_id' => $complete_form['form_build_id']['#value'],
         ],
       ],
-      'wrapper' => $element['#id'] . '-ajax-wrapper',
+      'wrapper' => $ajax_wrapper_id,
       'effect' => 'fade',
       'progress' => [
         'type' => $element['#progress_indicator'],
@@ -259,8 +261,12 @@ public static function processManagedFile(&$element, FormStateInterface $form_st
       $element['upload']['#attached']['drupalSettings']['file']['elements']['#' . $element['#id']] = $extension_list;
     }
 
+    // Let #id point to the file element, so the field label's 'for' corresponds
+    // with it.
+    $element['#id'] = &$element['upload']['#id'];
+
     // Prefix and suffix used for Ajax replacement.
-    $element['#prefix'] = '<div id="' . $element['#id'] . '-ajax-wrapper">';
+    $element['#prefix'] = '<div id="' . $ajax_wrapper_id . '">';
     $element['#suffix'] = '</div>';
 
     return $element;
diff --git a/core/modules/file/src/Tests/FileFieldWidgetTest.php b/core/modules/file/src/Tests/FileFieldWidgetTest.php
index ec02bb4..10f2cad 100644
--- a/core/modules/file/src/Tests/FileFieldWidgetTest.php
+++ b/core/modules/file/src/Tests/FileFieldWidgetTest.php
@@ -9,7 +9,6 @@
 
 use Drupal\comment\Entity\Comment;
 use Drupal\comment\Tests\CommentTestTrait;
-use Drupal\Component\Utility\Html;
 use Drupal\field\Entity\FieldConfig;
 use Drupal\field_ui\Tests\FieldUiTestTrait;
 use Drupal\user\RoleInterface;
@@ -86,7 +85,8 @@ function testSingleValuedWidget() {
       $this->assertNoFieldByXPath('//input[@type="submit"]', t('Remove'), 'After clicking the "Remove" button, it is no longer displayed.');
       $this->assertFieldByXpath('//input[@type="submit"]', t('Upload'), 'After clicking the "Remove" button, the "Upload" button is displayed.');
       // Test label has correct 'for' attribute.
-      $label = $this->xpath("//label[@for='edit-" . Html::cleanCssIdentifier($field_name) . "-0-upload']");
+      $input = $this->xpath('//input[@name="files[' . $field_name . '_0]"]');
+      $label = $this->xpath('//label[@for="' . (string) $input[0]['id'] . '"]');
       $this->assertTrue(isset($label[0]), 'Label for upload found.');
 
       // Save the node and ensure it does not have the file.
diff --git a/core/modules/image/src/Tests/ImageFieldDisplayTest.php b/core/modules/image/src/Tests/ImageFieldDisplayTest.php
index 74b07ed..8800020 100644
--- a/core/modules/image/src/Tests/ImageFieldDisplayTest.php
+++ b/core/modules/image/src/Tests/ImageFieldDisplayTest.php
@@ -251,15 +251,9 @@ function testImageFieldSettings() {
     $node_storage->resetCache(array($nid));
     $node = $node_storage->load($nid);
     $file = $node->{$field_name}->entity;
-    $image_style = array(
-      '#theme' => 'image_style',
-      '#uri' => $file->getFileUri(),
-      '#width' => 40,
-      '#height' => 20,
-      '#style_name' => 'medium',
-    );
-    $default_output = drupal_render($image_style);
-    $this->assertRaw($default_output, "Preview image is displayed using 'medium' style.");
+
+    $url = file_create_url(ImageStyle::load('medium')->buildUrl($file->getFileUri()));
+    $this->assertTrue($this->cssSelect('img[width=40][height=20][class=image-style-medium][src="' . $url . '"]'));
 
     // Add alt/title fields to the image and verify that they are displayed.
     $image = array(
diff --git a/core/modules/simpletest/src/AssertContentTrait.php b/core/modules/simpletest/src/AssertContentTrait.php
index 240aea9..54dba00 100644
--- a/core/modules/simpletest/src/AssertContentTrait.php
+++ b/core/modules/simpletest/src/AssertContentTrait.php
@@ -822,14 +822,13 @@ protected function assertThemeOutput($callback, array $variables = array(), $exp
   }
 
   /**
-   * Asserts that a field exists in the current page by the given XPath.
+   * Asserts that a field exists in the current page with a given Xpath result.
    *
-   * @param string $xpath
-   *   XPath used to find the field.
+   * @param \SimpleXmlElement[] $fields
+   *   Xml elements.
    * @param string $value
-   *   (optional) Value of the field to assert. You may pass in NULL (default)
-   *   to skip checking the actual value, while still checking that the field
-   *   exists.
+   *   (optional) Value of the field to assert. You may pass in NULL (default) to skip
+   *   checking the actual value, while still checking that the field exists.
    * @param string $message
    *   (optional) A message to display with the assertion. Do not translate
    *   messages: use format_string() to embed variables in the message text, not
@@ -843,9 +842,7 @@ protected function assertThemeOutput($callback, array $variables = array(), $exp
    * @return bool
    *   TRUE on pass, FALSE on fail.
    */
-  protected function assertFieldByXPath($xpath, $value = NULL, $message = '', $group = 'Other') {
-    $fields = $this->xpath($xpath);
-
+  protected function assertFieldsByValue($fields, $value = NULL, $message = '', $group = 'Other') {
     // If value specified then check array for match.
     $found = TRUE;
     if (isset($value)) {
@@ -881,6 +878,34 @@ protected function assertFieldByXPath($xpath, $value = NULL, $message = '', $gro
   }
 
   /**
+   * Asserts that a field exists in the current page by the given XPath.
+   *
+   * @param string $xpath
+   *   XPath used to find the field.
+   * @param string $value
+   *   (optional) Value of the field to assert. You may pass in NULL (default)
+   *   to skip checking the actual value, while still checking that the field
+   *   exists.
+   * @param string $message
+   *   (optional) A message to display with the assertion. Do not translate
+   *   messages: use format_string() to embed variables in the message text, not
+   *   t(). If left blank, a default message will be displayed.
+   * @param string $group
+   *   (optional) The group this message is in, which is displayed in a column
+   *   in test output. Use 'Debug' to indicate this is debugging output. Do not
+   *   translate this string. Defaults to 'Other'; most tests do not override
+   *   this default.
+   *
+   * @return bool
+   *   TRUE on pass, FALSE on fail.
+   */
+  protected function assertFieldByXPath($xpath, $value = NULL, $message = '', $group = 'Other') {
+    $fields = $this->xpath($xpath);
+
+    return $this->assertFieldsByValue($fields, $value, $message, $group);
+  }
+
+  /**
    * Get the selected value from a select field.
    *
    * @param \SimpleXmlElement $element
diff --git a/core/modules/simpletest/src/WebTestBase.php b/core/modules/simpletest/src/WebTestBase.php
index 3616888..c8cced7 100644
--- a/core/modules/simpletest/src/WebTestBase.php
+++ b/core/modules/simpletest/src/WebTestBase.php
@@ -19,6 +19,7 @@
 use Drupal\Core\Database\Database;
 use Drupal\Core\DrupalKernel;
 use Drupal\Core\Entity\EntityInterface;
+use Drupal\Core\EventSubscriber\AjaxSubscriber;
 use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
 use Drupal\Core\Render\Element;
 use Drupal\Core\Session\AccountInterface;
@@ -1693,13 +1694,7 @@ protected function drupalPostAjaxForm($path, $edit, $triggering_element, $ajax_p
         $extra_post[$key] = $value;
       }
     }
-    $ajax_html_ids = array();
-    foreach ($this->xpath('//*[@id]') as $element) {
-      $ajax_html_ids[] = (string) $element['id'];
-    }
-    if (!empty($ajax_html_ids)) {
-      $extra_post['ajax_html_ids'] = implode(' ', $ajax_html_ids);
-    }
+    $extra_post[AjaxSubscriber::AJAX_REQUEST_PARAMETER] = 1;
     $extra_post += $this->getAjaxPageStatePostData();
     // Now serialize all the $extra_post values, and prepend it with an '&'.
     $extra_post = '&' . $this->serializePostValues($extra_post);
diff --git a/core/modules/system/src/Controller/FormAjaxController.php b/core/modules/system/src/Controller/FormAjaxController.php
index 0c29322..65078a8 100644
--- a/core/modules/system/src/Controller/FormAjaxController.php
+++ b/core/modules/system/src/Controller/FormAjaxController.php
@@ -7,20 +7,15 @@
 
 namespace Drupal\system\Controller;
 
-use Drupal\Core\Ajax\AjaxResponse;
-use Drupal\Core\Ajax\UpdateBuildIdCommand;
 use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
+use Drupal\Core\Form\FormAjaxResponseBuilderInterface;
 use Drupal\Core\Form\FormState;
 use Drupal\Core\Form\FormBuilderInterface;
-use Drupal\Core\Render\MainContent\MainContentRendererInterface;
-use Drupal\Core\Render\RendererInterface;
-use Drupal\Core\Routing\RouteMatchInterface;
 use Drupal\system\FileAjaxForm;
 use Psr\Log\LoggerInterface;
 use Symfony\Component\DependencyInjection\ContainerInterface;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
-use Symfony\Component\HttpKernel\Exception\HttpException;
 
 /**
  * Defines a controller to respond to form Ajax requests.
@@ -42,25 +37,11 @@ class FormAjaxController implements ContainerInjectionInterface {
   protected $formBuilder;
 
   /**
-   * The renderer.
+   * The form AJAX response builder.
    *
-   * @var \Drupal\Core\Render\RendererInterface
+   * @var \Drupal\Core\Form\FormAjaxResponseBuilderInterface
    */
-  protected $renderer;
-
-  /**
-   * The main content to AJAX Response renderer.
-   *
-   * @var \Drupal\Core\Render\MainContent\MainContentRendererInterface
-   */
-  protected $ajaxRenderer;
-
-  /**
-   * The current route match.
-   *
-   * @var \Drupal\Core\Routing\RouteMatchInterface
-   */
-  protected $routeMatch;
+  protected $formAjaxResponseBuilder;
 
   /**
    * Constructs a FormAjaxController object.
@@ -69,19 +50,13 @@ class FormAjaxController implements ContainerInjectionInterface {
    *   A logger instance.
    * @param \Drupal\Core\Form\FormBuilderInterface $form_builder
    *   The form builder.
-   * @param \Drupal\Core\Render\RendererInterface $renderer
-   *   The renderer.
-   * @param \Drupal\Core\Render\MainContent\MainContentRendererInterface $ajax_renderer
-   *   The main content to AJAX Response renderer.
-   * @param \Drupal\Core\Routing\RouteMatchInterface
-   *   The current route match.
+   * @param \Drupal\Core\Form\FormAjaxResponseBuilderInterface $form_ajax_response_builder
+   *   The form AJAX response builder.
    */
-  public function __construct(LoggerInterface $logger, FormBuilderInterface $form_builder, RendererInterface $renderer, MainContentRendererInterface $ajax_renderer, RouteMatchInterface $route_match) {
+  public function __construct(LoggerInterface $logger, FormBuilderInterface $form_builder, FormAjaxResponseBuilderInterface $form_ajax_response_builder) {
     $this->logger = $logger;
     $this->formBuilder = $form_builder;
-    $this->renderer = $renderer;
-    $this->ajaxRenderer = $ajax_renderer;
-    $this->routeMatch = $route_match;
+    $this->formAjaxResponseBuilder = $form_ajax_response_builder;
   }
 
   /**
@@ -91,9 +66,7 @@ public static function create(ContainerInterface $container) {
     return new static(
       $container->get('logger.factory')->get('ajax'),
       $container->get('form_builder'),
-      $container->get('renderer'),
-      $container->get('main_content_renderer.ajax'),
-      $container->get('current_route_match')
+      $container->get('form_ajax_response_builder')
     );
   }
 
@@ -121,38 +94,7 @@ public function content(Request $request) {
 
     $this->formBuilder->processForm($form['#form_id'], $form, $form_state);
 
-    // We need to return the part of the form (or some other content) that needs
-    // to be re-rendered so the browser can update the page with changed content.
-    // Since this is the generic menu callback used by many Ajax elements, it is
-    // up to the #ajax['callback'] function of the element (may or may not be a
-    // button) that triggered the Ajax request to determine what needs to be
-    // rendered.
-    $callback = NULL;
-    if ($triggering_element = $form_state->getTriggeringElement()) {
-      $callback = $triggering_element['#ajax']['callback'];
-    }
-    $callback = $form_state->prepareCallback($callback);
-    if (empty($callback) || !is_callable($callback)) {
-      throw new HttpException(500, 'The specified #ajax callback is empty or not callable.');
-    }
-    $result = call_user_func_array($callback, [&$form, &$form_state]);
-
-    // If the callback is an #ajax callback, the result is a render array, and
-    // we need to turn it into an AJAX response, so that we can add any commands
-    // we got earlier; typically the UpdateBuildIdCommand when handling an AJAX
-    // submit from a cached page.
-    if ($result instanceof AjaxResponse) {
-      $response = $result;
-    }
-    else {
-      /** @var \Drupal\Core\Ajax\AjaxResponse $response */
-      $response = $this->ajaxRenderer->renderResponse($result, $request, $this->routeMatch);
-    }
-
-    foreach ($commands as $command) {
-      $response->addCommand($command, TRUE);
-    }
-    return $response;
+    return $this->formAjaxResponseBuilder->buildResponse($request, $form, $form_state, $commands);
   }
 
   /**
@@ -186,17 +128,6 @@ protected function getForm(Request $request) {
       throw new BadRequestHttpException();
     }
 
-    // When a page level cache is enabled, the form-build id might have been
-    // replaced from within \Drupal::formBuilder()->getCache(). If this is the
-    // case, it is also necessary to update it in the browser by issuing an
-    // appropriate Ajax command.
-    $commands = [];
-    if (isset($form['#build_id_old']) && $form['#build_id_old'] != $form['#build_id']) {
-      // If the form build ID has changed, issue an Ajax command to update it.
-      $commands[] = new UpdateBuildIdCommand($form['#build_id_old'], $form['#build_id']);
-      $form_build_id = $form['#build_id'];
-    }
-
     // Since some of the submit handlers are run, redirects need to be disabled.
     $form_state->disableRedirect();
 
@@ -213,7 +144,7 @@ protected function getForm(Request $request) {
     $form_state->setUserInput($request->request->all());
     $form_id = $form['#form_id'];
 
-    return new FileAjaxForm($form, $form_state, $form_id, $form_build_id, $commands);
+    return new FileAjaxForm($form, $form_state, $form_id, $form['#build_id'], []);
   }
 
 }
diff --git a/core/modules/system/src/Tests/Ajax/AjaxFormCacheTest.php b/core/modules/system/src/Tests/Ajax/AjaxFormCacheTest.php
new file mode 100644
index 0000000..b70040f
--- /dev/null
+++ b/core/modules/system/src/Tests/Ajax/AjaxFormCacheTest.php
@@ -0,0 +1,67 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\system\Tests\Ajax\AjaxFormCacheTest.
+ */
+
+namespace Drupal\system\Tests\Ajax;
+
+use Drupal\Core\Url;
+
+/**
+ * Tests the usage of form caching for AJAX forms.
+ *
+ * @group Ajax
+ */
+class AjaxFormCacheTest extends AjaxTestBase {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function testFormCacheUsage() {
+    /** @var \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface $key_value_expirable */
+    $key_value_expirable = \Drupal::service('keyvalue.expirable')->get('form');
+    $this->drupalLogin($this->rootUser);
+
+    // Ensure that the cache is empty.
+    $this->assertEqual(0, count($key_value_expirable->getAll()));
+
+    // Visit an AJAX form that is not cached, 3 times.
+    $uncached_form_url = Url::fromRoute('ajax_forms_test.commands_form');
+    $this->drupalGet($uncached_form_url);
+    $this->drupalGet($uncached_form_url);
+    $this->drupalGet($uncached_form_url);
+
+    // The number of cache entries should not have changed.
+    $this->assertEqual(0, count($key_value_expirable->getAll()));
+
+    // Visit a form that is explicitly cached, 3 times.
+    $cached_form_url = Url::fromRoute('ajax_forms_test.get_form');
+    $this->drupalGet($cached_form_url);
+    $this->drupalGet($cached_form_url);
+    $this->drupalGet($cached_form_url);
+
+    // The number of cache entries should be exactly 3.
+    $this->assertEqual(3, count($key_value_expirable->getAll()));
+  }
+
+  /**
+   * Tests AJAX forms in blocks.
+   */
+  public function testBlockForms() {
+    $this->container->get('module_installer')->install(['block', 'search']);
+    $this->rebuildContainer();
+    $this->container->get('router.builder')->rebuild();
+    $this->drupalLogin($this->rootUser);
+
+    $this->drupalPlaceBlock('search_form_block', ['weight' => -5]);
+    $this->drupalPlaceBlock('ajax_forms_test_block', ['cache' => ['max_age' => 0]]);
+
+    $this->drupalGet('');
+    $this->drupalPostAjaxForm(NULL, ['test1' => 'option1'], 'test1');
+    $this->assertOptionSelected('edit-test1--2', 'option1');
+    $this->assertOption('edit-test1--2', 'option3');
+  }
+
+}
diff --git a/core/modules/system/src/Tests/Ajax/AjaxFormPageCacheTest.php b/core/modules/system/src/Tests/Ajax/AjaxFormPageCacheTest.php
index c5dafbe..03727b6 100644
--- a/core/modules/system/src/Tests/Ajax/AjaxFormPageCacheTest.php
+++ b/core/modules/system/src/Tests/Ajax/AjaxFormPageCacheTest.php
@@ -54,9 +54,15 @@ public function testSimpleAJAXFormValue() {
    $this->assertCommand($commands, $expected, 'Build id change command issued on first AJAX submission');
 
    $edit = ['select' => 'red'];
-   $this->drupalPostAjaxForm(NULL, $edit, 'select');
+   $commands = $this->drupalPostAjaxForm(NULL, $edit, 'select');
    $build_id_second_ajax = $this->getFormBuildId();
-   $this->assertEqual($build_id_first_ajax, $build_id_second_ajax, 'Build id remains the same on subsequent AJAX submissions');
+   $this->assertNotEqual($build_id_first_ajax, $build_id_second_ajax, 'Build id changes on subsequent AJAX submissions');
+   $expected = [
+     'command' => 'update_build_id',
+     'old' => $build_id_first_ajax,
+     'new' => $build_id_second_ajax,
+   ];
+   $this->assertCommand($commands, $expected, 'Build id change command issued on subsequent AJAX submissions');
 
    // Repeat the test sequence but this time with a page loaded from the cache.
    $this->drupalGet('ajax_forms_test_get_form');
@@ -77,9 +83,15 @@ public function testSimpleAJAXFormValue() {
    $this->assertCommand($commands, $expected, 'Build id change command issued on first AJAX submission');
 
    $edit = ['select' => 'red'];
-   $this->drupalPostAjaxForm(NULL, $edit, 'select');
+   $commands = $this->drupalPostAjaxForm(NULL, $edit, 'select');
    $build_id_from_cache_second_ajax = $this->getFormBuildId();
-   $this->assertEqual($build_id_from_cache_first_ajax, $build_id_from_cache_second_ajax, 'Build id remains the same on subsequent AJAX submissions');
+   $this->assertNotEqual($build_id_from_cache_first_ajax, $build_id_from_cache_second_ajax, 'Build id changes on subsequent AJAX submissions');
+   $expected = [
+     'command' => 'update_build_id',
+     'old' => $build_id_from_cache_first_ajax,
+     'new' => $build_id_from_cache_second_ajax,
+   ];
+   $this->assertCommand($commands, $expected, 'Build id change command issued on subsequent AJAX submissions');
  }
 
   /**
diff --git a/core/modules/system/src/Tests/Ajax/DialogTest.php b/core/modules/system/src/Tests/Ajax/DialogTest.php
index e290977..8412cc4 100644
--- a/core/modules/system/src/Tests/Ajax/DialogTest.php
+++ b/core/modules/system/src/Tests/Ajax/DialogTest.php
@@ -8,6 +8,7 @@
 namespace Drupal\system\Tests\Ajax;
 
 use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
+use Drupal\Core\Form\FormBuilderInterface;
 use Drupal\Core\Url;
 
 /**
@@ -124,6 +125,10 @@ public function testDialog() {
       // Don't send a target.
       'submit' => array()
     ));
+    // Make sure the selector ID starts with the right string.
+    $this->assert(strpos($ajax_result[3]['selector'], $no_target_expected_response['selector']) === 0, 'Selector starts with right string.');
+    unset($ajax_result[3]['selector']);
+    unset($no_target_expected_response['selector']);
     $this->assertEqual($no_target_expected_response, $ajax_result[3], 'Normal dialog with no target JSON response matches.');
 
     // Emulate closing the dialog via an AJAX request. There is no non-JS
@@ -146,11 +151,11 @@ public function testDialog() {
     $this->assertTrue($dialog_js_exists, 'Drupal dialog JS added to the page.');
 
     // Check that the response matches the expected value.
-    $this->assertEqual($modal_expected_response, $ajax_result[3], 'POST request modal dialog JSON response matches.');
+    $this->assertEqual($modal_expected_response, $ajax_result[4], 'POST request modal dialog JSON response matches.');
 
     // Abbreviated test for "normal" dialogs, testing only the difference.
     $ajax_result = $this->drupalPostAjaxForm('ajax-test/dialog', array(), 'button2');
-    $this->assertEqual($normal_expected_response, $ajax_result[3], 'POST request normal dialog JSON response matches.');
+    $this->assertEqual($normal_expected_response, $ajax_result[4], 'POST request normal dialog JSON response matches.');
 
     // Check that requesting a form dialog without JS goes to a page.
     $this->drupalGet('ajax-test/dialog-form');
@@ -165,7 +170,10 @@ public function testDialog() {
       'edit-preview' => [
         'callback' => '::preview',
         'event' => 'click',
-        'url' => Url::fromRoute('system.ajax')->toString(),
+        'url' => Url::fromRoute('ajax_test.dialog_form', [], ['query' => [
+            FormBuilderInterface::AJAX_FORM_REQUEST => TRUE,
+            MainContentViewSubscriber::WRAPPER_FORMAT => 'html',
+          ]])->toString(),
         'dialogType' => 'ajax',
         'submit' => [
           '_triggering_element_name' => 'op',
diff --git a/core/modules/system/src/Tests/Ajax/MultiFormTest.php b/core/modules/system/src/Tests/Ajax/MultiFormTest.php
index 449861c..47f3aa1 100644
--- a/core/modules/system/src/Tests/Ajax/MultiFormTest.php
+++ b/core/modules/system/src/Tests/Ajax/MultiFormTest.php
@@ -58,10 +58,9 @@ function testMultiForm() {
     // each Ajax submission, but these variables are stable and help target the
     // desired elements.
     $field_name = 'field_ajax_test';
-    $field_xpaths = array(
-      'node-page-form' => '//form[@id="node-page-form"]//div[contains(@class, "field-name-field-ajax-test")]',
-      'node-page-form--2' => '//form[@id="node-page-form--2"]//div[contains(@class, "field-name-field-ajax-test")]',
-    );
+
+    $form_xpath = '//form[starts-with(@id, "node-page-form")]';
+    $field_xpath = '//div[contains(@class, "field-name-field-ajax-test")]';
     $button_name = $field_name . '_add_more';
     $button_value = t('Add another item');
     $button_xpath_suffix = '//input[@name="' . $button_name . '"]';
@@ -71,19 +70,28 @@ function testMultiForm() {
     // of field items and "add more" button for the multi-valued field within
     // each form.
     $this->drupalGet('form-test/two-instances-of-same-form');
-    foreach ($field_xpaths as $field_xpath) {
-      $this->assert(count($this->xpath($field_xpath . $field_items_xpath_suffix)) == 1, 'Found the correct number of field items on the initial page.');
-      $this->assertFieldByXPath($field_xpath . $button_xpath_suffix, NULL, 'Found the "add more" button on the initial page.');
+
+    $fields = $this->xpath($form_xpath . $field_xpath);
+    $this->assertEqual(count($fields), 2);
+    foreach ($fields as $field) {
+      $this->assertEqual(count($field->xpath('.' . $field_items_xpath_suffix)), 1, 'Found the correct number of field items on the initial page.');
+      $this->assertFieldsByValue($field->xpath('.' . $button_xpath_suffix), NULL, 'Found the "add more" button on the initial page.');
     }
+
     $this->assertNoDuplicateIds(t('Initial page contains unique IDs'), 'Other');
 
     // Submit the "add more" button of each form twice. After each corresponding
     // page update, ensure the same as above.
-    foreach ($field_xpaths as $form_html_id => $field_xpath) {
-      for ($i = 0; $i < 2; $i++) {
-        $this->drupalPostAjaxForm(NULL, array(), array($button_name => $button_value), 'system/ajax', array(), array(), $form_html_id);
-        $this->assert(count($this->xpath($field_xpath . $field_items_xpath_suffix)) == $i+2, 'Found the correct number of field items after an AJAX submission.');
-        $this->assertFieldByXPath($field_xpath . $button_xpath_suffix, NULL, 'Found the "add more" button after an AJAX submission.');
+    for ($i = 0; $i < 2; $i++) {
+      $forms = $this->xpath($form_xpath);
+      foreach ($forms as $offset => $form) {
+        $form_html_id = (string) $form['id'];
+        $this->drupalPostAjaxForm(NULL, array(), array($button_name => $button_value), NULL, array(), array(), $form_html_id);
+        $form = $this->xpath($form_xpath)[$offset];
+        $field = $form->xpath('.' . $field_xpath);
+
+        $this->assertEqual(count($field[0]->xpath('.' . $field_items_xpath_suffix)), $i+2, 'Found the correct number of field items after an AJAX submission.');
+        $this->assertFieldsByValue($field[0]->xpath('.' . $button_xpath_suffix), NULL, 'Found the "add more" button after an AJAX submission.');
         $this->assertNoDuplicateIds(t('Updated page contains unique IDs'), 'Other');
       }
     }
diff --git a/core/modules/system/src/Tests/Form/RebuildTest.php b/core/modules/system/src/Tests/Form/RebuildTest.php
index e993b49..53de2f2 100644
--- a/core/modules/system/src/Tests/Form/RebuildTest.php
+++ b/core/modules/system/src/Tests/Form/RebuildTest.php
@@ -96,7 +96,7 @@ function testPreserveFormActionAfterAJAX() {
     // submission and verify it worked by ensuring the updated page has two text
     // field items in the field for which we just added an item.
     $this->drupalGet('node/add/page');
-    $this->drupalPostAjaxForm(NULL, array(), array('field_ajax_test_add_more' => t('Add another item')), 'system/ajax', array(), array(), 'node-page-form');
+    $this->drupalPostAjaxForm(NULL, array(), array('field_ajax_test_add_more' => t('Add another item')), NULL, array(), array(), 'node-page-form');
     $this->assert(count($this->xpath('//div[contains(@class, "field-name-field-ajax-test")]//input[@type="text"]')) == 2, 'AJAX submission succeeded.');
 
     // Submit the form with the non-Ajax "Save" button, leaving the title field
@@ -113,6 +113,9 @@ function testPreserveFormActionAfterAJAX() {
 
     // Ensure that the form's action is correct.
     $forms = $this->xpath('//form[contains(@class, "node-page-form")]');
-    $this->assert(count($forms) == 1 && $forms[0]['action'] == Url::fromRoute('node.add', ['node_type' => 'page'])->toString(), 'Re-rendered form contains the correct action value.');
+    $this->assertEqual(1, count($forms));
+    // Strip query params off the action before asserting.
+    $url = parse_url($forms[0]['action'])['path'];
+    $this->assertEqual(Url::fromRoute('node.add', ['node_type' => 'page'])->toString(), $url);
   }
 }
diff --git a/core/modules/system/tests/modules/ajax_forms_test/src/Form/AjaxFormsTestSimpleForm.php b/core/modules/system/tests/modules/ajax_forms_test/src/Form/AjaxFormsTestSimpleForm.php
index 225664d..1f76850 100644
--- a/core/modules/system/tests/modules/ajax_forms_test/src/Form/AjaxFormsTestSimpleForm.php
+++ b/core/modules/system/tests/modules/ajax_forms_test/src/Form/AjaxFormsTestSimpleForm.php
@@ -10,6 +10,7 @@
 use Drupal\Core\Form\FormBase;
 use Drupal\ajax_forms_test\Callbacks;
 use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Url;
 
 /**
  * Form builder: Builds a form that triggers a simple AJAX callback.
@@ -68,7 +69,11 @@ public function buildForm(array $form, FormStateInterface $form_state) {
         '#type' => 'select',
         '#title' => $this->t('Test %key callbacks', array('%key' => $key)),
         '#options' => array('red' => 'red'),
-        '#ajax' => array('callback' => $value),
+        '#ajax' => array(
+          'callback' => $value,
+          // If the callback is NULL, the URL needs to be specified.
+          'url' => $value === NULL ? Url::fromRoute('system.ajax') : NULL,
+        ),
       );
     }
 
diff --git a/core/modules/system/tests/modules/ajax_forms_test/src/Plugin/Block/AjaxFormBlock.php b/core/modules/system/tests/modules/ajax_forms_test/src/Plugin/Block/AjaxFormBlock.php
new file mode 100644
index 0000000..a588378
--- /dev/null
+++ b/core/modules/system/tests/modules/ajax_forms_test/src/Plugin/Block/AjaxFormBlock.php
@@ -0,0 +1,132 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\ajax_forms_test\Plugin\Block\AjaxFormBlock.
+ */
+
+namespace Drupal\ajax_forms_test\Plugin\Block;
+
+use Drupal\Core\Block\BlockBase;
+use Drupal\Core\Form\FormBuilderInterface;
+use Drupal\Core\Form\FormInterface;
+use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+
+/**
+ * Provides an AJAX form block.
+ *
+ * @Block(
+ *   id = "ajax_forms_test_block",
+ *   admin_label = @Translation("AJAX test form"),
+ *   category = @Translation("Forms")
+ * )
+ */
+class AjaxFormBlock extends BlockBase implements FormInterface, ContainerFactoryPluginInterface {
+
+  /**
+   * The form builder.
+   *
+   * @var \Drupal\Core\Form\FormBuilderInterface
+   */
+  protected $formBuilder;
+
+  /**
+   * Constructs a new AjaxFormBlock.
+   *
+   * @param array $configuration
+   *   A configuration array containing information about the plugin instance.
+   * @param string $plugin_id
+   *   The plugin ID for the plugin instance.
+   * @param mixed $plugin_definition
+   *   The plugin implementation definition.
+   * @param \Drupal\Core\Form\FormBuilderInterface $form_builder
+   *   The form builder.
+   */
+  public function __construct(array $configuration, $plugin_id, $plugin_definition, FormBuilderInterface $form_builder) {
+    parent::__construct($configuration, $plugin_id, $plugin_definition);
+    $this->formBuilder = $form_builder;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
+    return new static(
+      $configuration,
+      $plugin_id,
+      $plugin_definition,
+      $container->get('form_builder')
+    );
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function build() {
+    return $this->formBuilder->getForm($this);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getFormId() {
+    return 'ajax_forms_test_block';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function buildForm(array $form, FormStateInterface $form_state) {
+    $form['test1'] = [
+      '#type' => 'select',
+      '#title' => $this->t('Test 1'),
+      '#required' => TRUE,
+      '#options' => [
+        'option1' => $this->t('Option 1'),
+        'option2' => $this->t('Option 2'),
+      ],
+      '#ajax' => [
+        'callback' => '::updateOptions',
+        'wrapper' => 'edit-test1-wrapper',
+      ],
+      '#prefix' => '<div id="edit-test1-wrapper">',
+      '#suffix' => '</div>',
+    ];
+    return $form;
+  }
+
+  /**
+   * Updates the options of a select list.
+   *
+   * @param array $form
+   *   An associative array containing the structure of the form.
+   * @param \Drupal\Core\Form\FormStateInterface $form_state
+   *   The current state of the form.
+   *
+   * @return array
+   *   The updated form element.
+   */
+  public function updateOptions(array $form, FormStateInterface $form_state) {
+    $form['test1']['#options']['option1'] = $this->t('Option 1!!!');
+    $form['test1']['#options'] += [
+      'option3' => $this->t('Option 3'),
+      'option4' => $this->t('Option 4'),
+    ];
+    return $form['test1'];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function validateForm(array &$form, FormStateInterface $form_state) {
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function submitForm(array &$form, FormStateInterface $form_state) {
+  }
+
+}
diff --git a/core/modules/views/src/Controller/ViewAjaxController.php b/core/modules/views/src/Controller/ViewAjaxController.php
index 2608344..6a5264c 100644
--- a/core/modules/views/src/Controller/ViewAjaxController.php
+++ b/core/modules/views/src/Controller/ViewAjaxController.php
@@ -12,6 +12,7 @@
 use Drupal\Core\Ajax\ReplaceCommand;
 use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
 use Drupal\Core\Entity\EntityStorageInterface;
+use Drupal\Core\EventSubscriber\AjaxSubscriber;
 use Drupal\Core\Path\CurrentPathStack;
 use Drupal\Core\Render\RendererInterface;
 use Drupal\Core\Routing\RedirectDestinationInterface;
@@ -133,7 +134,7 @@ public function ajaxView(Request $request) {
 
       // Remove all of this stuff from the query of the request so it doesn't
       // end up in pagers and tablesort URLs.
-      foreach (array('view_name', 'view_display_id', 'view_args', 'view_path', 'view_dom_id', 'pager_element', 'view_base_path', 'ajax_html_ids') as $key) {
+      foreach (array('view_name', 'view_display_id', 'view_args', 'view_path', 'view_dom_id', 'pager_element', 'view_base_path', AjaxSubscriber::AJAX_REQUEST_PARAMETER) as $key) {
         $request->query->remove($key);
         $request->request->remove($key);
       }
diff --git a/core/modules/views_ui/admin.inc b/core/modules/views_ui/admin.inc
index 64b9077..7e07366 100644
--- a/core/modules/views_ui/admin.inc
+++ b/core/modules/views_ui/admin.inc
@@ -51,6 +51,11 @@ function views_ui_add_ajax_trigger(&$wrapping_element, $trigger_key, $refresh_pa
   // Add the AJAX behavior to the triggering element.
   $triggering_element = &$wrapping_element[$trigger_key];
   $triggering_element['#ajax']['callback'] = 'views_ui_ajax_update_form';
+
+  // Specify the #ajax URL in order to retain form caching.
+  // @todo Remove this in https://www.drupal.org/node/2500523.
+  $triggering_element['#ajax']['url'] = Url::fromRoute('system.ajax');
+
   // We do not use \Drupal\Component\Utility\Html::getUniqueId() to get an ID
   // for the AJAX wrapper, because it remembers IDs across AJAX requests (and
   // won't reuse them), but in our case we need to use the same ID from request
diff --git a/core/modules/views_ui/js/views-admin.js b/core/modules/views_ui/js/views-admin.js
index 17b16d5..4fbcae0 100644
--- a/core/modules/views_ui/js/views-admin.js
+++ b/core/modules/views_ui/js/views-admin.js
@@ -21,7 +21,7 @@
     attach: function () {
       // Only show the SQL rewrite warning when the user has chosen the
       // corresponding checkbox.
-      $('#edit-query-options-disable-sql-rewrite').on('click', function () {
+      $('[data-drupal-selector="edit-query-options-disable-sql-rewrite"]').on('click', function () {
         $('.sql-rewrite-warning').toggleClass('js-hide');
       });
     }
@@ -412,7 +412,7 @@
     /**
      * Add a keyup handler to the search box.
      */
-    this.$searchBox = this.$form.find('#edit-override-controls-options-search');
+    this.$searchBox = this.$form.find('[data-drupal-selector="edit-override-controls-options-search"]');
     this.$searchBox.on('keyup', $.proxy(this.handleKeyup, this));
 
     /**
@@ -950,25 +950,27 @@ else if ($row.hasClass('draggable') && $row.is(':visible')) {
    */
   Drupal.behaviors.viewsFilterConfigSelectAll = {
     attach: function (context) {
-      // Show the select all checkbox.
-      $(context).find('#views-ui-handler-form div.form-item-options-value-all').once('filterConfigSelectAll')
-        .show()
-        .find('input[type=checkbox]')
-        .on('click', function () {
-          var checked = $(this).is(':checked');
+      var $context = $(context);
+
+      var $selectAll = $context.find('.form-item-options-value-all').once('filterConfigSelectAll');
+      var $selectAllCheckbox = $selectAll.find('input[type=checkbox]');
+      var $checkboxes = $selectAll.closest('.form-checkboxes').find('.js-form-type-checkbox:not(.form-item-options-value-all) input[type="checkbox"]');
+
+      if ($selectAll.length) {
+         // Show the select all checkbox.
+        $selectAll.show();
+        $selectAllCheckbox.on('click', function () {
           // Update all checkbox beside the select all checkbox.
-          $(this).parents('.form-checkboxes').find('input[type=checkbox]').each(function () {
-            $(this).attr('checked', checked);
-          });
+          $checkboxes.prop('checked', $(this).is(':checked'));
         });
-      // Uncheck the select all checkbox if any of the others are unchecked.
-      $('#views-ui-handler-form').find('div.js-form-type-checkbox').not($('.form-item-options-value-all'))
-        .find('input[type=checkbox]')
-        .on('click', function () {
+
+        // Uncheck the select all checkbox if any of the others are unchecked.
+        $checkboxes.on('click', function () {
           if ($(this).is('checked') === false) {
-            $('#edit-options-value-all').prop('checked', false);
+            $selectAllCheckbox.prop('checked', false);
           }
         });
+      }
     }
   };
 
@@ -990,7 +992,7 @@ else if ($row.hasClass('draggable') && $row.is(':visible')) {
    */
   Drupal.behaviors.viewsUiCheckboxify = {
     attach: function (context, settings) {
-      var $buttons = $('#edit-options-expose-button-button, #edit-options-group-button-button').once('views-ui-checkboxify');
+      var $buttons = $('[data-drupal-selector="edit-options-expose-button-button"], [data-drupal-selector="edit-options-group-button-button"]').once('views-ui-checkboxify');
       var length = $buttons.length;
       var i;
       for (i = 0; i < length; i++) {
@@ -1066,7 +1068,7 @@ function changeDefaultWidget(event) {
    */
   Drupal.behaviors.viewsUiOverrideSelect = {
     attach: function (context) {
-      $(context).find('#edit-override-dropdown').once('views-ui-override-button-text').each(function () {
+      $(context).find('[data-drupal-selector="edit-override-dropdown"]').once('views-ui-override-button-text').each(function () {
         // Closures! :(
         var $context = $(context);
         var $submit = $context.find('[id^=edit-submit]');
diff --git a/core/modules/views_ui/src/ViewUI.php b/core/modules/views_ui/src/ViewUI.php
index 6532689..4837ce1 100644
--- a/core/modules/views_ui/src/ViewUI.php
+++ b/core/modules/views_ui/src/ViewUI.php
@@ -12,6 +12,7 @@
 use Drupal\Component\Utility\Timer;
 use Drupal\Component\Utility\Xss;
 use Drupal\Core\Config\Entity\ThirdPartySettingsInterface;
+use Drupal\Core\EventSubscriber\AjaxSubscriber;
 use Drupal\Core\Form\FormStateInterface;
 use Drupal\Core\Url;
 use Drupal\views\Views;
@@ -582,7 +583,7 @@ public function renderPreview($display_id, $args = array()) {
       // have some input in the query parameters, so we merge request() and
       // query() to ensure we get it all.
       $exposed_input = array_merge(\Drupal::request()->request->all(), \Drupal::request()->query->all());
-      foreach (array('view_name', 'view_display_id', 'view_args', 'view_path', 'view_dom_id', 'pager_element', 'view_base_path', 'ajax_html_ids', 'ajax_page_state', 'form_id', 'form_build_id', 'form_token') as $key) {
+      foreach (array('view_name', 'view_display_id', 'view_args', 'view_path', 'view_dom_id', 'pager_element', 'view_base_path', AjaxSubscriber::AJAX_REQUEST_PARAMETER, 'ajax_page_state', 'form_id', 'form_build_id', 'form_token') as $key) {
         if (isset($exposed_input[$key])) {
           unset($exposed_input[$key]);
         }
diff --git a/core/tests/Drupal/Tests/Component/Utility/HtmlTest.php b/core/tests/Drupal/Tests/Component/Utility/HtmlTest.php
index 18b07f7..0addf3c 100644
--- a/core/tests/Drupal/Tests/Component/Utility/HtmlTest.php
+++ b/core/tests/Drupal/Tests/Component/Utility/HtmlTest.php
@@ -143,19 +143,25 @@ public function providerTestHtmlGetUniqueId() {
    *   The expected result.
    * @param string $source
    *   The string being transformed to an ID.
-   * @param bool $reset
-   *   (optional) If TRUE, reset the list of seen IDs. Defaults to FALSE.
    *
    * @dataProvider providerTestHtmlGetUniqueIdWithAjaxIds
    *
    * @covers ::getUniqueId
    */
-  public function testHtmlGetUniqueIdWithAjaxIds($expected, $source, $reset = FALSE) {
-    if ($reset) {
-      Html::resetSeenIds();
+  public function testHtmlGetUniqueIdWithAjaxIds($expected, $source) {
+    Html::setIsAjax(TRUE);
+    $id = Html::getUniqueId($source);
+
+    // Note, we truncate two hyphens at the end.
+    // @see \Drupal\Component\Utility\Html::getId()
+    if (strpos($source, '--') !== FALSE) {
+      $random_suffix = substr($id, strlen($source) + 1);
     }
-    Html::setAjaxHtmlIds('test-unique-id1 test-unique-id2--3');
-    $this->assertSame($expected, Html::getUniqueId($source));
+    else {
+      $random_suffix = substr($id, strlen($source) + 2);
+    }
+    $expected = $expected . $random_suffix;
+    $this->assertSame($expected, $id);
   }
 
   /**
@@ -166,10 +172,11 @@ public function testHtmlGetUniqueIdWithAjaxIds($expected, $source, $reset = FALS
    */
   public function providerTestHtmlGetUniqueIdWithAjaxIds() {
     return array(
-      array('test-unique-id1--2', 'test-unique-id1', TRUE),
-      array('test-unique-id1--3', 'test-unique-id1'),
-      array('test-unique-id2--4', 'test-unique-id2', TRUE),
-      array('test-unique-id2--5', 'test-unique-id2'),
+      array('test-unique-id1--', 'test-unique-id1'),
+      // Note, we truncate two hyphens at the end.
+      // @see \Drupal\Component\Utility\Html::getId()
+      array('test-unique-id1---', 'test-unique-id1--'),
+      array('test-unique-id2--', 'test-unique-id2'),
     );
   }
 
@@ -186,6 +193,7 @@ public function providerTestHtmlGetUniqueIdWithAjaxIds() {
    * @covers ::getId
    */
   public function testHtmlGetId($expected, $source) {
+    Html::setIsAjax(FALSE);
     $this->assertSame($expected, Html::getId($source));
   }
 
diff --git a/core/tests/Drupal/Tests/Core/Form/EventSubscriber/FormAjaxSubscriberTest.php b/core/tests/Drupal/Tests/Core/Form/EventSubscriber/FormAjaxSubscriberTest.php
new file mode 100644
index 0000000..eb01501
--- /dev/null
+++ b/core/tests/Drupal/Tests/Core/Form/EventSubscriber/FormAjaxSubscriberTest.php
@@ -0,0 +1,196 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\Tests\Core\Form\EventSubscriber\FormAjaxSubscriberTest.
+ */
+
+namespace Drupal\Tests\Core\Form\EventSubscriber;
+
+use Drupal\Core\Form\EventSubscriber\FormAjaxSubscriber;
+use Drupal\Core\Form\FormAjaxException;
+use Drupal\Core\Form\FormState;
+use Drupal\Tests\UnitTestCase;
+use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\HttpFoundation\Response;
+use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
+use Symfony\Component\HttpKernel\Exception\HttpException;
+use Symfony\Component\HttpKernel\HttpKernelInterface;
+
+/**
+ * @coversDefaultClass \Drupal\Core\Form\EventSubscriber\FormAjaxSubscriber
+ * @group EventSubscriber
+ */
+class FormAjaxSubscriberTest extends UnitTestCase {
+
+  /**
+   * @var \Drupal\Core\Form\EventSubscriber\FormAjaxSubscriber
+   */
+  protected $subscriber;
+
+  /**
+   * @var \Drupal\Core\Form\FormAjaxResponseBuilderInterface|\PHPUnit_Framework_MockObject_MockObject
+   */
+  protected $formAjaxResponseBuilder;
+
+  /**
+   * @var \Symfony\Component\HttpKernel\HttpKernelInterface|\PHPUnit_Framework_MockObject_MockObject
+   */
+  protected $httpKernel;
+
+  /**
+   * {@inheritdoc}
+   */
+  protected function setUp() {
+    parent::setUp();
+
+    $this->httpKernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
+    $this->formAjaxResponseBuilder = $this->getMock('Drupal\Core\Form\FormAjaxResponseBuilderInterface');
+    $this->subscriber = new FormAjaxSubscriber($this->formAjaxResponseBuilder);
+  }
+
+  /**
+   * @covers ::onException
+   */
+  public function testOnException() {
+    $form = ['#type' => 'form', '#build_id' => 'the_build_id'];
+    $expected_form = $form + [
+      '#build_id_old' => 'the_build_id',
+    ];
+    $form_state = new FormState();
+    $exception = new FormAjaxException($form, $form_state);
+
+    $request = new Request([], ['form_build_id' => 'the_build_id']);
+    $commands = [];
+    $response = new Response('');
+
+    $this->formAjaxResponseBuilder->expects($this->once())
+      ->method('buildResponse')
+      ->with($request, $expected_form, $form_state, $commands)
+      ->willReturn($response);
+
+    $event = $this->assertResponseFromException($request, $exception, $response);
+    $this->assertSame(200, $event->getResponse()->headers->get('X-Status-Code'));
+  }
+
+  /**
+   * @covers ::onException
+   */
+  public function testOnExceptionNewBuildId() {
+    $form = ['#type' => 'form', '#build_id' => 'the_build_id'];
+    $expected_form = $form + [
+      '#build_id_old' => 'a_new_build_id',
+    ];
+    $form_state = new FormState();
+    $exception = new FormAjaxException($form, $form_state);
+
+    $request = new Request([], ['form_build_id' => 'a_new_build_id']);
+    $commands = [];
+    $response = new Response('');
+
+    $this->formAjaxResponseBuilder->expects($this->once())
+      ->method('buildResponse')
+      ->with($request, $expected_form, $form_state, $commands)
+      ->willReturn($response);
+
+    $event = $this->assertResponseFromException($request, $exception, $response);
+    $this->assertSame(200, $event->getResponse()->headers->get('X-Status-Code'));
+  }
+
+  /**
+   * @covers ::onException
+   */
+  public function testOnExceptionOtherClass() {
+    $request = new Request();
+    $exception = new \Exception();
+
+    $this->formAjaxResponseBuilder->expects($this->never())
+      ->method('buildResponse');
+
+    $this->assertResponseFromException($request, $exception, NULL);
+  }
+
+  /**
+   * @covers ::onException
+   */
+  public function testOnExceptionResponseBuilderException() {
+    $form = ['#type' => 'form', '#build_id' => 'the_build_id'];
+    $expected_form = $form + [
+      '#build_id_old' => 'the_build_id',
+    ];
+    $form_state = new FormState();
+    $exception = new FormAjaxException($form, $form_state);
+    $request = new Request([], ['form_build_id' => 'the_build_id']);
+    $commands = [];
+
+    $expected_exception = new HttpException(500, 'The specified #ajax callback is empty or not callable.');
+    $this->formAjaxResponseBuilder->expects($this->once())
+      ->method('buildResponse')
+      ->with($request, $expected_form, $form_state, $commands)
+      ->willThrowException($expected_exception);
+
+    $event = $this->assertResponseFromException($request, $exception, NULL);
+    $this->assertSame($expected_exception, $event->getException());
+  }
+
+  /**
+   * @covers ::onException
+   * @covers ::getFormAjaxException
+   */
+  public function testOnExceptionNestedException() {
+    $form = ['#type' => 'form', '#build_id' => 'the_build_id'];
+    $expected_form = $form + [
+        '#build_id_old' => 'the_build_id',
+      ];
+    $form_state = new FormState();
+    $form_exception = new FormAjaxException($form, $form_state);
+    $exception = new \Exception('', 0, $form_exception);
+
+    $request = new Request([], ['form_build_id' => 'the_build_id']);
+    $commands = [];
+    $response = new Response('');
+
+    $this->formAjaxResponseBuilder->expects($this->once())
+      ->method('buildResponse')
+      ->with($request, $expected_form, $form_state, $commands)
+      ->willReturn($response);
+
+    $this->assertResponseFromException($request, $exception, $response);
+  }
+
+  /**
+   * @covers ::getFormAjaxException
+   */
+  public function testOnExceptionNestedWrongException() {
+    $nested_exception = new \Exception();
+    $exception = new \Exception('', 0, $nested_exception);
+    $request = new Request();
+
+    $this->formAjaxResponseBuilder->expects($this->never())
+      ->method('buildResponse');
+
+    $this->assertResponseFromException($request, $exception, NULL);
+  }
+
+  /**
+   * Asserts that the expected response is derived from the given exception.
+   *
+   * @param \Symfony\Component\HttpFoundation\Request $request
+   *   The request.
+   * @param \Exception $exception
+   *   The exception to pass to the event.
+   * @param \Symfony\Component\HttpFoundation\Response|null $expected_response
+   *   The response expected to be set on the event.
+   *
+   * @return \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent
+   *   The event used to derive the response.
+   */
+  protected function assertResponseFromException(Request $request, \Exception $exception, $expected_response) {
+    $event = new GetResponseForExceptionEvent($this->httpKernel, $request, HttpKernelInterface::MASTER_REQUEST, $exception);
+    $this->subscriber->onException($event);
+
+    $this->assertSame($expected_response, $event->getResponse());
+    return $event;
+  }
+
+}
diff --git a/core/tests/Drupal/Tests/Core/Form/FormAjaxResponseBuilderTest.php b/core/tests/Drupal/Tests/Core/Form/FormAjaxResponseBuilderTest.php
new file mode 100644
index 0000000..0698e28
--- /dev/null
+++ b/core/tests/Drupal/Tests/Core/Form/FormAjaxResponseBuilderTest.php
@@ -0,0 +1,212 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\Tests\Core\Form\FormAjaxResponseBuilderTest.
+ */
+
+namespace Drupal\Tests\Core\Form;
+
+use Drupal\Core\Ajax\AjaxResponse;
+use Drupal\Core\Ajax\AlertCommand;
+use Drupal\Core\Form\FormAjaxResponseBuilder;
+use Drupal\Core\Form\FormState;
+use Drupal\Core\Form\FormStateInterface;
+use Drupal\Tests\UnitTestCase;
+use Symfony\Component\HttpFoundation\Request;
+
+/**
+ * @coversDefaultClass \Drupal\Core\Form\FormAjaxResponseBuilder
+ * @group Form
+ */
+class FormAjaxResponseBuilderTest extends UnitTestCase {
+
+  /**
+   * @var \Drupal\Core\Render\MainContent\MainContentRendererInterface|\PHPUnit_Framework_MockObject_MockObject
+   */
+  protected $renderer;
+
+  /**
+   * @var \Drupal\Core\Routing\RouteMatchInterface|\PHPUnit_Framework_MockObject_MockObject
+   */
+  protected $routeMatch;
+
+  /**
+   * @var \Drupal\Core\Form\FormAjaxResponseBuilder
+   */
+  protected $formAjaxResponseBuilder;
+
+  /**
+   * {@inheritdoc}
+   */
+  protected function setUp() {
+    parent::setUp();
+    $this->renderer = $this->getMock('Drupal\Core\Render\MainContent\MainContentRendererInterface');
+    $this->routeMatch = $this->getMock('Drupal\Core\Routing\RouteMatchInterface');
+    $this->formAjaxResponseBuilder = new FormAjaxResponseBuilder($this->renderer, $this->routeMatch);
+  }
+
+  /**
+   * @covers ::buildResponse
+   *
+   * @expectedException \Symfony\Component\HttpKernel\Exception\HttpException
+   */
+  public function testBuildResponseNoTriggeringElement() {
+    $this->renderer->expects($this->never())
+      ->method('renderResponse');
+
+    $request = new Request();
+    $form = [];
+    $form_state = new FormState();
+    $commands = [];
+
+    $expected = [];
+    $this->assertSame($expected, $this->formAjaxResponseBuilder->buildResponse($request, $form, $form_state, $commands));
+  }
+
+  /**
+   * @covers ::buildResponse
+   *
+   * @expectedException \Symfony\Component\HttpKernel\Exception\HttpException
+   */
+  public function testBuildResponseNoCallable() {
+    $this->renderer->expects($this->never())
+      ->method('renderResponse');
+
+    $request = new Request();
+    $form = [];
+    $form_state = new FormState();
+    $triggering_element = [];
+    $form_state->setTriggeringElement($triggering_element);
+    $commands = [];
+
+    $expected = [];
+    $this->assertSame($expected, $this->formAjaxResponseBuilder->buildResponse($request, $form, $form_state, $commands));
+  }
+
+  /**
+   * @covers ::buildResponse
+   */
+  public function testBuildResponseRenderArray() {
+    $triggering_element = [
+      '#ajax' => [
+        'callback' => function (array $form, FormStateInterface $form_state) {
+          return $form['test'];
+        }
+      ],
+    ];
+    $request = new Request();
+    $form = [
+      'test' => [
+        '#type' => 'textfield',
+      ],
+    ];
+    $form_state = new FormState();
+    $form_state->setTriggeringElement($triggering_element);
+    $commands = [];
+
+    $this->renderer->expects($this->once())
+      ->method('renderResponse')
+      ->with($form['test'], $request, $this->routeMatch)
+      ->willReturn(new AjaxResponse([]));
+
+    $result = $this->formAjaxResponseBuilder->buildResponse($request, $form, $form_state, $commands);
+    $this->assertInstanceOf('\Drupal\Core\Ajax\AjaxResponse', $result);
+    $this->assertSame($commands, $result->getCommands());
+  }
+
+  /**
+   * @covers ::buildResponse
+   */
+  public function testBuildResponseResponse() {
+    $triggering_element = [
+      '#ajax' => [
+        'callback' => function (array $form, FormStateInterface $form_state) {
+          return new AjaxResponse([]);
+        }
+      ],
+    ];
+    $request = new Request();
+    $form = [];
+    $form_state = new FormState();
+    $form_state->setTriggeringElement($triggering_element);
+    $commands = [];
+
+    $this->renderer->expects($this->never())
+      ->method('renderResponse');
+
+    $result = $this->formAjaxResponseBuilder->buildResponse($request, $form, $form_state, $commands);
+    $this->assertInstanceOf('\Drupal\Core\Ajax\AjaxResponse', $result);
+    $this->assertSame($commands, $result->getCommands());
+  }
+
+  /**
+   * @covers ::buildResponse
+   */
+  public function testBuildResponseWithCommands() {
+    $triggering_element = [
+      '#ajax' => [
+        'callback' => function (array $form, FormStateInterface $form_state) {
+          return new AjaxResponse([]);
+        }
+      ],
+    ];
+    $request = new Request();
+    $form = [
+      'test' => [
+        '#type' => 'textfield',
+      ],
+    ];
+    $form_state = new FormState();
+    $form_state->setTriggeringElement($triggering_element);
+    $commands = [
+      new AlertCommand('alert!'),
+    ];
+    $commands_expected = [];
+    $commands_expected[] = ['command' => 'alert', 'text' => 'alert!'];
+
+    $this->renderer->expects($this->never())
+      ->method('renderResponse');
+
+    $result = $this->formAjaxResponseBuilder->buildResponse($request, $form, $form_state, $commands);
+    $this->assertInstanceOf('\Drupal\Core\Ajax\AjaxResponse', $result);
+    $this->assertSame($commands_expected, $result->getCommands());
+  }
+
+  /**
+   * @covers ::buildResponse
+   */
+  public function testBuildResponseWithUpdateCommand() {
+    $triggering_element = [
+      '#ajax' => [
+        'callback' => function (array $form, FormStateInterface $form_state) {
+          return new AjaxResponse([]);
+        }
+      ],
+    ];
+    $request = new Request();
+    $form = [
+      '#build_id' => 'the_build_id',
+      '#build_id_old' => 'a_new_build_id',
+      'test' => [
+        '#type' => 'textfield',
+      ],
+    ];
+    $form_state = new FormState();
+    $form_state->setTriggeringElement($triggering_element);
+    $commands = [
+      new AlertCommand('alert!'),
+    ];
+    $commands_expected = [];
+    $commands_expected[] = ['command' => 'update_build_id', 'old' => 'a_new_build_id', 'new' => 'the_build_id'];
+    $commands_expected[] = ['command' => 'alert', 'text' => 'alert!'];
+
+    $this->renderer->expects($this->never())
+      ->method('renderResponse');
+
+    $result = $this->formAjaxResponseBuilder->buildResponse($request, $form, $form_state, $commands);
+    $this->assertInstanceOf('\Drupal\Core\Ajax\AjaxResponse', $result);
+    $this->assertSame($commands_expected, $result->getCommands());
+  }
+
+}
