protected function getAjaxErrorResponse(ValidationResult $result)
    {
        // Ajax form submissions accept json encoded errors by default
        $acceptType = $this->getRequest()->getHeader('Accept');
        if (strpos($acceptType, 'application/json') !== false) {
            // Send validation errors back as JSON with a flag at the start
            $response = new HTTPResponse(json_encode($result->getMessages()));
            $response->addHeader('Content-Type', 'application/json');
            return $response;
        }

        // Send the newly rendered form tag as HTML
        $this->form->loadMessagesFrom($result);
        $response = new HTTPResponse($this->form->forTemplate());
        $response->addHeader('Content-Type', 'text/html');
        return $response;
    }