Symfony2, check if an action is called by ajax or not

Clément Andraud picture Clément Andraud · May 28, 2014 · Viewed 28.2k times · Source

I need, for each action in my controller, check if these actions are called by an ajax request or not.

If yes, nothing append, if no, i need to redirect to the home page.

I have just find if($this->getRequest()->isXmlHttpRequest()), but i need to add this verification on each action..

Do you know a better way ?

Answer

R. Canser Yanbakan picture R. Canser Yanbakan · May 28, 2014

It's very easy!

Just add $request variable 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 you want to do that automatically, you have to define a kernel request listener.