How to generate twif url symfony url with parameter value from javascript?

I want to add query string parameters from javascript (jquery) to symfony 2 url. I want to pass the value of the selected switch to an ajax request, for example, in simple php. I would do it like

$(document).ready(function() {
    $('.id_radio').click(function() {                      
        $.ajax({
            'url': 'example.php?id='+($this).val(),
            'success': function(r) {
                $('#div1').html(r);
            }
        });
    });

How to create such a url in symfony2 twig? We generate the url in symfony 2 twig like

{{ path('example_path', {'id': id}) }} where id is the variable of the variable.

I tried using the FOSJsRoutingBundle, but I don’t know if it is for the same problem and not sure how to use it?

I tried below, but it does not work.

$('.id_radio').click(function() {
    alert(Routing.generate('example_path', {
        'id': $(this).val()
        }));
    $.ajax({
        'url': Routing.generate('example_path', {
            'id': $(this).val()
            }),
        'success': function(r) {
            $('#div1').html(r);
        }
    });
});

The solution mentioned below in koskoz's work, I did not pass options = {"expose" = true}, but after adding it.

. , . , . , symfony.

, .

+4
3

/**
 * @Route("/example/{name}", name="example_path", options={"expose"=true})
 * @Template
 */
public function exampleAction($name)
{

}

FOSJsRoutingBundle

$('.id_radio').click(function() {
    alert(Routing.generate('example_path', {'id': $(this).val()}));
    $.ajax({
        'url': Routing.generate('example_path', {'id': $(this).val()}),
        'success': function(r) {
            $('#div1').html(r);
        }
    });
});

,

     /**
     * @Route("/example", name="example_path", options={"expose"=true})
     * @Method({"GET"})
     * @Template 
     */
    public function exampleAction()
    {


    }

$('.id_radio').click(function() {
    $.ajax({
        'url': '{{ path('example_path') }}',
        'data': 'name='+$(this).val(),
        'type': 'GET',
        'success': function(r) {
            $('#div1').html(r);
        }
    });
});
+1

, FOSJsRoutingBundle :

, JavaScript, JS, - :

Routing.generate('my_route_to_expose', { id: 10 });
+3

fosjsrouting : https://github.com/FriendsOfSymfony/FOSJsRoutingBundle

:   expose: true

And in your js file add url = Routing.generate ('route_name', {parameter: parameter_value});

+1
source

All Articles