How to integrate Ajax with Symfony2 [closed]
I'm looking form simple tutorial/example about ajax in symfony2, for beginner?
I have these examples:
city.php: http://pastebin.com/Qm8LS5kh
ajax_req.js: http://pastebin.com/UqJMad24
index.html: http://pastebin.com/H1err4Yh
How can these be put into a Symfony2 app?
Solution 1:
It is easy. I will illustrate how to do an AJAX call in Symfony2 through 3 steps. For the following example, assume to use the jQuery library.
-
Define the route for the action that has to handle your AJAX call. E.g.
AcmeHomeBundle_ajax_update_mydata: pattern: /update/data/from/ajax/call defaults: { _controller: AcmeHomeBundle:MyAjax:updateData }
-
Define the action in the
MyAjax
controller fromHome
bundle. E.g.public function updateDataAction(){ $request = $this->container->get('request'); $data1 = $request->query->get('data1'); $data2 = $request->query->get('data2'); ... //handle data ... //prepare the response, e.g. $response = array("code" => 100, "success" => true); //you can return result as JSON return new Response(json_encode($response)); }
-
Prepare your
AJAX
call in yourTwig
template, e.g.:function aButtonPressed(){ $.post('{{path('AcmeHomeBundle_ajax_update_mydata')}}', {data1: 'mydata1', data2:'mydata2'}, function(response){ if(response.code == 100 && response.success){//dummy check //do something } }, "json"); } $(document).ready(function() { $('button').on('click', function(){aButtonPressed();}); });
You can change the example by using other AJAX calls.