Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle errors in Ajax within Symfony2 controller

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

like image 691
Mick Avatar asked Sep 12 '12 10:09

Mick


People also ask

Which method is used on the returned object of AJAX () method if the AJAX call fails?

If an AJAX request fails, you can react to the failure inside the callback function added via the fail() function of the object returned by the $. ajax() function. Here is a jQuery AJAX error handling example: var jqxhr = $.


1 Answers

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);
}
like image 83
Florian Eckerstorfer Avatar answered Oct 17 '22 21:10

Florian Eckerstorfer