How to integrate Ajax with Symfony2 [closed]

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 from Home 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 your Twig 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.

Leave a Comment