I’m a beginner in Symfony (version 2), I have a project achieved with plain basic PHP, and now I’m redoing my pages in dealing with Symfony framework, and arrived to my jquery ajax functions, surely, things gonna be different, I used to do like this:
JavaScript
x
4
1
$("#div").click(function(){
2
$.post("targetFile.php",{/*parameters*/,function(data){ });
3
});
4
Q: How to make that works on Symfony? What to put instead of targetFile.php? a route most probably. and what to do on the controller and router sides? I looked out on Google and here, but didn’t get any clear answers. Regards.
Advertisement
Answer
If you set inside routing.yml this:
JavaScript
1
5
1
_admin_ajax:
2
resource: "@SomethingAdminBundle/Controller/AjaxController.php"
3
type: annotation
4
prefix: /admin/ajax
5
… and inside controller, that will handle ajax call this:
JavaScript
1
13
13
1
/**
2
* @Route("/ajaxhandler", name="_admin_ajax_handler")
3
*/
4
public function handlerAction() {
5
6
$isAjax = $this->get('Request')->isXMLHttpRequest();
7
if ($isAjax) {
8
//...
9
return new Response('This is ajax response');
10
}
11
return new Response('This is not ajax!', 400);
12
}
13
… then inside for example TWIG template you should call it like this:
JavaScript
1
4
1
$("#div").click(function(){
2
$.post("{{ url('_admin_items_add') }}",{/*parameters*/,function(data){ });
3
});
4
… and the real route for your action will be generated with templating engine.