Handle errors in Ajax within Symfony2 controller

Mick picture Mick · Sep 12, 2012 · Viewed 8.3k times · Source

I am trying to handle errors in Ajax. For this, I am simply trying to reproduce this SO question in Symfony.

$.ajaxSetup({
    error: function(xhr){
        alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
    }
});

but I can't figure out what the code in the controller would look like in Symfony2 to trigger header('HTTP/1.0 419 Custom Error');. Is it possible to attach a personal message with this, for example You are not allowed to delete this post. Do I need to send a JSON response too?

If anyone is familiar with this, I would really appreciate your help.

Many thanks

Answer

Florian Eckerstorfer picture Florian Eckerstorfer · Sep 12, 2012

In your action you can return a Symfony\Component\HttpFoundation\Response object and you can either use the setStatusCode method or the second constructor argument to set the HTTP status code. Of course if is also possible to return the content of the response as JSON (or XML) if you want to:

public function ajaxAction()
{
    $content = json_encode(array('message' => 'You are not allowed to delete this post'));
    return new Response($content, 419);
}

or

public function ajaxAction()
{
    $response = new Response();
    $response->setContent(json_encode(array('message' => 'You are not allowed to delete this post'));
    $response->setStatusCode(419);
    return $response;
}

Update: If you are using Symfony 2.1 you can return an instance of Symfony\Component\HttpFoundation\JsonResponse (Thanks to thecatontheflat for the hint). Using this class has the advantage that it will also send the correct Content-type header. For example:

public function ajaxAction()
{
    return new JsonResponse(array('message' => ''), 419);
}