Ajax Response not returning

I have the following ‘handler’ for ajaxRequests in my AppController:

/**
 * @param array $messages
 * @return Response
 */
public function ajaxSuccessResponse(array $messages = []): Response
{
    return $this->ajaxResponse([
        'status' => 'success',
        'messages' => $messages
    ]);
}

/**
 * @param array $messages
 * @return Response
 */
public function ajaxErrorResponse(array $messages = []): Response
{
    return $this->ajaxResponse([
        'status' => 'error',
        'messages' => $messages
    ]);
}

/**
 * @param array $response
 * @return Response
 */
private function ajaxResponse(array $response): Response
{
    $this->viewBuilder()->setTemplate('ajax');
    $this->response->withType('json');
    $this->response->withStringBody(json_encode($response));
    return $this->response;
}

When I call a method that needs to handle ajax requests, I call it like so:

return $this->ajaxErrorResponse(['Some error message.']);

When I use the below javascript, my response is empty (when I check it on Google Chrome’s network tab)

$.post({
    url: 'my-url',
    headers: {
        'X-CSRF-Token': csrfToken
    },
    data: {
        username: $('input[name="username"]').val(),
        password: $('input[name="password"]').val(),
        url: $('input[name="url"]').val()
    },
    dataType: "json"
});

What am I doing wrong? If I echo the response, I get an exception that says result should be either Response or null.

The response object is immutable. Try this:

private function ajaxResponse(array $response): Response
{
    $this->viewBuilder()->setTemplate('ajax');
    return $this->response
        ->withType('json')
        ->withStringBody(json_encode($response));
}

Thank you, this worked.