class AjaxResponse

JSON response object for AJAX requests.

Hierarchy

Expanded class hierarchy of AjaxResponse

1 file declares its use of AjaxResponse
file.module in drupal/core/modules/file/file.module
Defines a "managed_file" Form API field and a "file" field for Field module.

File

drupal/core/lib/Drupal/Core/Ajax/AjaxResponse.php, line 16
Definition of Drupal\Core\Ajax\AjaxResponse.

Namespace

Drupal\Core\Ajax
View source
class AjaxResponse extends JsonResponse {

  /**
   * The array of ajax commands.
   *
   * @var array
   */
  protected $commands = array();

  /**
   * Add an AJAX command to the response.
   *
   * @param object $command
   *   An AJAX command object implementing CommandInterface.
   * @param boolean $prepend
   *   A boolean which determines whether the new command should be executed
   *   before previously added commands. Defaults to FALSE.
   *
   * @return AjaxResponse
   *   The current AjaxResponse.
   */
  public function addCommand($command, $prepend = FALSE) {
    if ($prepend) {
      array_unshift($this->commands, $command
        ->render());
    }
    else {
      $this->commands[] = $command
        ->render();
    }
    return $this;
  }

  /**
   * Sets the response's data to be the array of AJAX commands.
   *
   * @param Request $request
   *   A request object.
   *
   * @return
   *   Response The current response.
   */
  public function prepare(Request $request) {
    parent::setData($this
      ->ajaxRender($request));
    return parent::prepare($request);
  }

  /**
   * Prepares the AJAX commands for sending back to the client.
   *
   * @param Request $request
   *   The request object that the AJAX is responding to.
   *
   * @return array
   *   An array of commands ready to be returned as JSON.
   */
  protected function ajaxRender(Request $request) {

    // Ajax responses aren't rendered with html.tpl.php, so we have to call
    // drupal_get_css() and drupal_get_js() here, in order to have new files
    // added during this request to be loaded by the page. We only want to send
    // back files that the page hasn't already loaded, so we implement simple
    // diffing logic using array_diff_key().
    $ajax_page_state = $request->request
      ->get('ajax_page_state');
    foreach (array(
      'css',
      'js',
    ) as $type) {

      // It is highly suspicious if $_POST['ajax_page_state'][$type] is empty,
      // since the base page ought to have at least one JS file and one CSS file
      // loaded. It probably indicates an error, and rather than making the page
      // reload all of the files, instead we return no new files.
      if (empty($ajax_page_state[$type])) {
        $items[$type] = array();
      }
      else {
        $function = 'drupal_add_' . $type;
        $items[$type] = $function();
        drupal_alter($type, $items[$type]);

        // @todo Inline CSS and JS items are indexed numerically. These can't be
        //   reliably diffed with array_diff_key(), since the number can change
        //   due to factors unrelated to the inline content, so for now, we
        //   strip the inline items from Ajax responses, and can add support for
        //   them when drupal_add_css() and drupal_add_js() are changed to using
        //   md5() or some other hash of the inline content.
        foreach ($items[$type] as $key => $item) {
          if (is_numeric($key)) {
            unset($items[$type][$key]);
          }
        }

        // Ensure that the page doesn't reload what it already has.
        $items[$type] = array_diff_key($items[$type], $ajax_page_state[$type]);
      }
    }

    // Render the HTML to load these files, and add AJAX commands to insert this
    // HTML in the page. We pass TRUE as the $skip_alter argument to prevent the
    // data from being altered again, as we already altered it above. Settings
    // are handled separately, afterwards.
    if (isset($items['js']['settings'])) {
      unset($items['js']['settings']);
    }
    $styles = drupal_get_css($items['css'], TRUE);
    $scripts_footer = drupal_get_js('footer', $items['js'], TRUE);
    $scripts_header = drupal_get_js('header', $items['js'], TRUE);

    // Prepend commands to add the resources, preserving their relative order.
    $resource_commands = array();
    if (!empty($styles)) {
      $resource_commands[] = new AddCssCommand($styles);
    }
    if (!empty($scripts_header)) {
      $resource_commands[] = new PrependCommand('head', $scripts_header);
    }
    if (!empty($scripts_footer)) {
      $resource_commands[] = new AppendCommand('body', $scripts_footer);
    }
    foreach (array_reverse($resource_commands) as $resource_command) {
      $this
        ->addCommand($resource_command, TRUE);
    }

    // Prepend a command to merge changes and additions to Drupal.settings.
    $scripts = drupal_add_js();
    if (!empty($scripts['settings'])) {
      $settings = $scripts['settings'];
      $this
        ->addCommand(new SettingsCommand(call_user_func_array('array_merge_recursive', $settings['data']), TRUE), TRUE);
    }
    $commands = $this->commands;
    drupal_alter('ajax_render', $commands);
    return $commands;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AjaxResponse::$commands protected property The array of ajax commands.
AjaxResponse::addCommand public function Add an AJAX command to the response.
AjaxResponse::ajaxRender protected function Prepares the AJAX commands for sending back to the client.
AjaxResponse::prepare public function Sets the response's data to be the array of AJAX commands. Overrides Response::prepare
JsonResponse::$callback protected property
JsonResponse::$data protected property
JsonResponse::create public static function Factory method for chainability Overrides Response::create
JsonResponse::setCallback public function Sets the JSONP callback.
JsonResponse::setData public function Sets the data to be sent as json.
JsonResponse::update protected function Updates the content and headers according to the json data and callback.
JsonResponse::__construct public function Constructor. Overrides Response::__construct
Response::$charset protected property
Response::$content protected property
Response::$headers public property
Response::$statusCode protected property
Response::$statusText protected property
Response::$statusTexts public static property Status codes translation table.
Response::$version protected property
Response::expire public function Marks the response stale by setting the Age header to be equal to the maximum age of the response.
Response::getAge public function Returns the age of the response.
Response::getCharset public function Retrieves the response charset.
Response::getContent public function Gets the current response content. 1
Response::getDate public function Returns the Date header as a DateTime instance.
Response::getEtag public function Returns the literal value of the ETag HTTP header.
Response::getExpires public function Returns the value of the Expires header as a DateTime instance.
Response::getLastModified public function Returns the Last-Modified HTTP header as a DateTime instance.
Response::getMaxAge public function Sets the number of seconds after the time specified in the response's Date header when the the response should no longer be considered fresh.
Response::getProtocolVersion public function Gets the HTTP protocol version.
Response::getStatusCode public function Retrieves the status code for the current web response.
Response::getTtl public function Returns the response's time-to-live in seconds.
Response::getVary public function Returns an array of header names given in the Vary header.
Response::hasVary public function Returns true if the response includes a Vary header.
Response::isCacheable public function Returns true if the response is worth caching under any circumstance.
Response::isClientError public function Is there a client error?
Response::isEmpty public function Is the response empty?
Response::isForbidden public function Is the reponse forbidden?
Response::isFresh public function Returns true if the response is "fresh".
Response::isInformational public function Is response informative?
Response::isInvalid public function Is response invalid?
Response::isNotFound public function Is the response a not found error?
Response::isNotModified public function Determines if the Response validators (ETag, Last-Modified) match a conditional value specified in the Request.
Response::isOk public function Is the response OK?
Response::isRedirect public function Is the response a redirect of some form?
Response::isRedirection public function Is the response a redirect?
Response::isServerError public function Was there a server side error?
Response::isSuccessful public function Is response successful?
Response::isValidateable public function Returns true if the response includes headers that can be used to validate the response with the origin server using a conditional GET request.
Response::mustRevalidate public function Returns true if the response must be revalidated by caches.
Response::send public function Sends HTTP headers and content.
Response::sendContent public function Sends content for the current web response. 1
Response::sendHeaders public function Sends HTTP headers.
Response::setCache public function Sets the response's cache headers (validation and/or expiration).
Response::setCharset public function Sets the response charset.
Response::setClientTtl public function Sets the response's time-to-live for private/client caches.
Response::setContent public function Sets the response content. 1
Response::setDate public function Sets the Date header.
Response::setEtag public function Sets the ETag value.
Response::setExpires public function Sets the Expires HTTP header with a DateTime instance.
Response::setLastModified public function Sets the Last-Modified HTTP header with a DateTime instance.
Response::setMaxAge public function Sets the number of seconds after which the response should no longer be considered fresh.
Response::setNotModified public function Modifies the response so that it conforms to the rules defined for a 304 status code.
Response::setPrivate public function Marks the response as "private".
Response::setProtocolVersion public function Sets the HTTP protocol version (1.0 or 1.1).
Response::setPublic public function Marks the response as "public".
Response::setSharedMaxAge public function Sets the number of seconds after which the response should no longer be considered fresh by shared caches.
Response::setStatusCode public function Sets the response status code.
Response::setTtl public function Sets the response's time-to-live for shared caches.
Response::setVary public function Sets the Vary header.
Response::__clone public function Clones the current Response instance.
Response::__toString public function Returns the Response as an HTTP string.