I'm trying to use a jquery varaible inside a twig template to send by ajax, but I can't access to the jquery variable inside the twig:
My code is:
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#my_input").change(function(){
var value = jQuery("#my_input").val();
jQuery.ajax({
url: "{{ path('ParteAccidentes_ajax', {'emergencia': value}) }}",
timeout: 5000,
success: function(data) {
alert('ok');
},
error: function() {
alert('mal');
}
});
});
});
</script>
The error show is variable value doesn't exist (in "url:..." line)
Thanks!
The problem is that Twig is launched before than JavaScript and the variable "id_emergencia" is not recognized by Twig. You could do a trick. You can put a string, as a parameter and then, in the JavaScript code, you replace the string with the value of your variable. In this way, you will always have the correct url before your AJAX petition is launched.
You could do something like this:
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#my_input").change(function(){
var value = jQuery("#my_input").val();
var url = "{{ path('ParteAccidentes_ajax', {'emergencia': 'text'}) }}";
url = url.replace("text", value);
jQuery.ajax({
url: url,
timeout: 5000,
success: function(data) {
alert ('ok');
},
error: function() { alert ('mal');
}
});
});
});
</script>
Of course it does not exist.
The value
variable is just plain text for Twig. Remember:
First the Twig parts are rendered, then it gets outputted to the browser, then the Browser renders the content and executes the Javascript.
The line {{ path('ParteAccidentes_ajax', {'emergencia': value}) }}
is executed way before value
is event parsed as javascript.
Also you're doing this in an event handler.
How should twig (since it's just a PHP library) change the path url on a executed javascript event?
Since you just want to update an URL based on symfony paths and a javascript variable, please have a look at this bundle: https://github.com/FriendsOfSymfony/FOSJsRoutingBundle
It provides the exact functionality you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With