如何在Symfony中使用Ajax?

I have a page with a list of items and some controls that are used for searching/sorting these items. I want these controls to work dynamically, using Ajax, but I can't find a way to use it in Symfony.

In plain PHP, I had the JS file that collected the data, then sent it to a PHP file, which triggered specified method from a class. How can I do something like that in Symfony3? Only tutorial I found was for Symfony 1.x.

If you are in a form, you can do something like :

$(document).submit(function () {
    var url = $('form').attr('action');
    var data = $('form').serialize();

    $.post(url, data, function (data) {
        window.location.href = data.redirect;
    })
        .fail(function () {
            $('form').replaceWith(data.form);
        });
});

You just need to send the correct url :

$(document).on('click', 'a', function () {
        var url = window.location.href;

        $.get(url, function (data) {
            $('.container').replaceWith(data);
        });
});

It is also possible to use a routing generator, simply add: "friendsofsymfony/jsrouting-bundle": "dev-master" to your composer.json.

AppKernel.php :

new FOS\JsRoutingBundle\FOSJsRoutingBundle()

Then config it in your routing.yml :

fos_js_routing:
    resource: "@FOSJsRoutingBundle/Resources/config/routing/routing.xml"

And finally use "expose" arg in your routing :

@Route("/{table}/index", name="beta.index", options={"expose"=true})

I use annotation routing

In your JS :

var url = Routing.generate('beta.index', { 'table': 'foo' });

Hope it'll help you :)