Javascript -> symfony controller request

I have HomeController.php with function :

public function foo(Request $request) : Response
    {
        do something
    }

Also i have routes.yaml to acces this controller

app_foo:
    path: /foo
    controller: AppControllerHomeController::foo

The question is, how can i execute foo() by clicking on link generated in javascript dynamically. What have i tried:

<a href="{{ url(app_foo) }}"> link </a>

and

$(document).on('click', 'a', function () {
$.ajax({
    type: "POST",
    url: "/app_foo",

    dataType: "json",
    success: function(response) {
        console.log(response);
    }
});

Answer

You should be able to use the event object that you receive in the function callback and call event.preventDefault(); to stop the browser’s native click handler, and also $(this).attr('href') to get the href portion of the URL so that you aren’t hard-coding it. I haven’t tried this code, but it should generally work:

        $(document).on('click', 'a', function (event) {
            event.preventDefault();
            $.ajax({
                type: "POST",
                url: $(this).attr('href'),

                dataType: "json",
                success: function (response) {
                    console.log(response);
                }
            });
        });

Leave a Reply

Your email address will not be published. Required fields are marked *