Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 899
Clément Andraud Avatar asked May 28 '14 12:05

Clément Andraud


People also ask

How do you check if Ajax call is completed?

The ajaxStop() method specifies a function to run when ALL AJAX requests have completed. When an AJAX request completes, jQuery checks if there are any more AJAX requests. The function specified with the ajaxStop() method will run if no other requests are pending.


2 Answers

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.

like image 189
Canser Yanbakan Avatar answered Sep 27 '22 21:09

Canser Yanbakan


For a reusable technique, I use the following 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 extending layout.html.twig can automatically be stripped of all your standard markup when originated from Ajax.

Source

like image 22
Pierre de LESPINAY Avatar answered Sep 27 '22 20:09

Pierre de LESPINAY