[ACCEPTED]-Symfony2, check if an action is called by ajax or not-controller

Accepted answer
Score: 66

It's very easy!

Just add $request variable 3 to your method as use. (For each controller)

<?php
namespace YOUR\Bundle\Namespace

use Symfony\Component\HttpFoundation\Request;

class SliderController extends Controller
{

    public function someAction(Request $request)
    {
        if($request->isXmlHttpRequest()) {
            // Do something...
        } else {
            return $this->redirect($this->generateUrl('your_route'));
        }
    }

}

If 2 you want to do that automatically, you have 1 to define a kernel request listener.

Score: 10

For a reusable technique, I use the following 4 from the base template

{# app/Resources/views/layout.html.twig #}
{% extends app.request.xmlHttpRequest 
     ? '::ajax-layout.html.twig'
     : '::full-layout.html.twig' %}

So all your templates 3 extending layout.html.twig can automatically be stripped 2 of all your standard markup when originated 1 from Ajax.

Source

Score: 3

First of all, note that getRequest() is 19 deprecated, so get the request through an 18 argument in your action methods.

If you dont 17 want to polute your controller class with 16 the additional code, a solution is to write 15 an event listener which is a service.

You 14 can define it like this:

services:
    acme.request.listener:
        class: Acme\Bundle\NewBundle\EventListener\RequestListener
        arguments: [@request_stack]
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onRequestAction }

Then in the RequestListener 13 class, make a onRequestAction() method and 12 inject request stack through the constrcutor. Inside 11 onRequestAction(), you can get controller 10 name like this:

$this->requestStack->getCurrentRequest()->get('_controller');

It will return the controller 9 name and action (I think they are separated 8 by :). Parse the string and check if it 7 is the right controller. And if it is, also 6 check it is XmlHttpRequest like this:

$this->requestStack->getCurrentRequest()->isXmlHttpRequest();

If 5 it is not, you can redirect/forward.

Also 4 note, that this will be checked upon every 3 single request. If you check those things 2 directly in one of your controllers, you 1 will have a more light-weight solution.

More Related questions