0

I would like to know how to pass javascript variables values from twig to controller using href path in Symfony2. this is my code:

 <html>
<head>
    <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
    <script>
        var a = "hello";
        var b = "hi";
        var c = $('<a href="{{ path('ikproj_groupe_homepagegroupe1', {'id': a, 'num': b}) }}">send data</a>');
        $('body').append(c);
    </script>    
</body>
</html>

The problem is that it displays this message: Variable "a" does not exist . So, my question is: what is the correct code to do that?

2 Answers 2

1

You need to set a twig variable. Ex:

<script>
    {% set a = 'hello' %}
    {% set b = 'hi' %}
    var c = $('<a href="{{ path('ikproj_groupe_homepagegroupe1', {'id': a, 'num': b}) }}">send data</a>');
    $('body').append(c);
</script> 
Sign up to request clarification or add additional context in comments.

2 Comments

well, just one thing more, let's assume that we have this javascript variable: var groupid1 = parseInt(data1.groupid); ... how can I set it with twig? in fact, if I put {% set groupid1 = parseInt(data1.groupid) %} it displays this error message: The function "parseInt" does not exist . Thanks in advance.
You cant mix JavaScript` and twig. First is run on client side and second is executed on serverside (twig is already rendered when JS work).
1

I find the easiest approach to this is to set the path in the original template using an href (or possible a data) attribute like..

<a href="{{ path('route_name', {'id': a }) }}" 
            class="some-specific-class">Click</a>

Or using a data attribute..

<a href="#" data-href="{{ path('route_name', {'id': a }) }}" 
            class="some-specific-class">Click</a>

And then in the javascript use..

$('a.some-specific-class').on('click', function(e) {
    e.preventDefault();

    var href = $(this).attr('href');
    .. or
    var href = $(this).data('href');

    .. do things with href
});

Alternatively you could you the FOSJSRoutingBundle and pass the id in a data attribute and generate the route from that using..

$('a.something').on('click', function(e) {
    e.preventDefault();

    var id = $(this).data('id'),
        url = Routing.generate('rout_name', {'id': id });

    .. do stuff with url
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.