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/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?
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./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?
Share Improve this question asked Jul 10, 2014 at 9:57 NadimNadim 4041 gold badge11 silver badges32 bronze badges2 Answers
Reset to default 1You 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>
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
});