Ajax and Jquery in Symfony

You realy just have to replace the targetFile.php by a custom route of yours.

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 method indexAction of the SiteController of the AcmeHelloBundle will be called.


If you set inside routing.yml this:

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

... and inside controller, that will handle ajax call 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 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 generated with templating engine.