Ajax and jQuery in Symfony

I start working in Symfony (version 2), I have a project with simple basic PHP, and now I am redoing my pages in working with the Symfony infrastructure and, of course, I come to my jquery ajax functions will be different, I did like this:

$("#div").click(function(){ $.post("targetFile.php",{/*parameters*/,function(data){ }); }); 

Q: How to do it on Symfony? What should be put instead of targetFile.php? route most likely. and what to do on the controller and router side? I looked at Google here too, but did not get any clear answers. Best wishes.

+6
source share
2 answers

If you install inside routing.yml this is:

 _admin_ajax: resource: "@SomethingAdminBundle/Controller/AjaxController.php" type: annotation prefix: /admin/ajax 

... and inside the tha controller will handle the ajax call of this:

 /** * @Route("/ajaxhandler", name="_admin_ajax_handler") */ public function handlerAction() { $isAjax = $this->get('Request')->isXMLHttpRequest(); if ($isAjax) { //... return new Response('This is ajax response'); } return new Response('This is not ajax!', 400); } 

... then inside, for example, a TWIG template, you should call it like this:

 $("#div").click(function(){ $.post("{{ url('_admin_items_add') }}",{/*parameters*/,function(data){ }); }); 

... and the real route for your action will be created using the template engine.

+4
source

You really need to replace targetFile.php with your own route.

So, if you have this in your routing.yml:

 # app/config/routing.yml hello: pattern: /ajax/target defaults: { _controller: AcmeHelloBundle:Site:index } 

You can use this javascript:

 $("#div").click(function(){ $.post("/ajax/target",{/*parameters*/,function(data){ }); }); 

On the Symfony2 side, the indexAction SiteController method from AcmeHelloBundle is called.

+5
source

Source: https://habr.com/ru/post/898058/


All Articles