Khelben
Khelben

Reputation: 23

Calling a controller function through a button

I'm having some troubles using Symfony 2 and requests. I am reading some docs but it just confuses me. Can you clear this easy point for me ? Thanks.

I am creating a website with some articles that a user can add to his favorites. All the entities are ok, the mapping and the base too. I just have front problems.

I want a button on the article page which calls a function in my controller (which calls the right repository methods) and don't refresh the page (that's why I can't use PHP only). I am thinking about changing the color of the button if the call works.

What do you use for that ? I don't need the result, I know how stackoverflow works, just foo/bar steps or name methods.

Thanks.

Upvotes: 1

Views: 4392

Answers (1)

Bartłomiej Wach
Bartłomiej Wach

Reputation: 1986

What you want to use here is jQuery.

U need a route in the controller to refer to:

/**
 * @Route("/do_something", name="your_action_route")
 */
public function doSomethingAction(Request $request) {

And then you can ad js script in your twig template:

$(document).on('click','button',function(){
     $.ajax('{{ path('your_action_route') }}', {
                    data: { 
                            // you can pass some parameters to the controller here
                    },
                    success: function(data) {
                            // change button color
                    },
                    error: function() {
                            // show alert or something
                    }
                });
    return false; // this stops normal button behaviour from executing;

});

This way, whenever you click a button on your site, the ajax request will execute your action in controller.

Upvotes: 4

Related Questions