Is it possible to restrict a route for AJAX only? Is it possible to restrict a route for AJAX only? symfony symfony

Is it possible to restrict a route for AJAX only?


I know this question is a bit older but meanwhile a new way to achieve this was introduced in Symfony 2.4.

Matching Expressions

For an ajax restriction it would look like this:

contact:    path:     /contact    defaults: { _controller: AcmeDemoBundle:Main:contact }    condition: "request.isXmlHttpRequest()"

Also possible in Annotation:

/** * ContactAction * * @Route("/contact", name="contact", condition="request.isXmlHttpRequest()") */


My advice would be to define your own router service instead of default, which would extend from Symfony\Bundle\FrameworkBundle\Routing\Router, and redefine method resolveParameters() with implementing your own logic for handling additional requirements.

And then, you could do something like this in your routing:

your_route:    pattern:  /somepattern    defaults: { somedefaults }    requirements:        _request_type:  some_requirement


I'm not sure that you can prevent the request taking place, however you can check for an XHR request in the Controller by checking the current Request

The code would look like this:

if ($request->isXmlHttpRequest()) {    // ...}

This is not 100% reliable, due to among other things, browser inconsistencies and the possibility of proxy interference. However it is the predominant method of checking for an asynchronous request and is recommended by many. If you are cr

URL Parameter

An alternative would be to add a parameter in your URL to identify the request as asynchronous. This is achieved by adding ?ajax=1 to your URL. Then, check for the parameter with:

$AjaxRequest = $request->getParameter('ajax');If($AjaxRequest == 1) {    //...}

Of course, at this point you could also create a specific Route e.g. /ajax/index/.