Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to restrict a route for AJAX only?

Tags:

ajax

php

symfony

Is it possible to restrict a Symfony 2 route for XHR requests only? I want to declare routes, which are only accessible via AJAX.

I do not want to put some extra lines into each AJAX-specific-actions like that:

if ($request->isXmlHttpRequest()) {     // do something } else {     // do something else } 

I want to define:

  • one rule for AJAX requests
  • one rule for GET/POST requests to the same URL

in order to get around having conditions like above.

like image 890
Chris Avatar asked Jul 19 '12 09:07

Chris


People also ask

Is there a limit to Ajax calls?

By default, the JavaScript Agent limits the Ajax requests (using XHR or the Fetch API) sent for base or virtual pages. The limit is 250 requests for single-page applications (SPAs) and 50 for non-SPAs.

How route is defined in Ajax?

Laravel Ajax Form Validation Tutorial so open your routes/web. php file and add the following route. Location:- Root/routes/web. php Route::get('my-form','HomeController@myform'); Route::post('my-form','HomeController@myformPost')->name('my.

What is route in Symfony?

When your application receives a request, it calls a controller action to generate the response. The routing configuration defines which action to run for each incoming URL. It also provides other useful features, like generating SEO-friendly URLs (e.g. /read/intro-to-symfony instead of index.


2 Answers

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()")  */ 
like image 162
Markus Kottländer Avatar answered Sep 21 '22 03:09

Markus Kottländer


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 
like image 33
Vitalii Zurian Avatar answered Sep 17 '22 03:09

Vitalii Zurian