I assume this question is already quite old, but I came across the same problem.
This is not a “best practice” solution, but here is what I do.
In twig you can use this {{ path('yourRouteName') }} thing in a perfect way. So in my twig file I have this structure:
... <a href="{{ path('myRoute') }}"> //results in eg http://localhost/app_dev.php/myRoute <div id="clickMe">Click</div> </a>
Now, if someone clicks on a div, I do the following in a .js file :
$('#clickMe').on('click', function(event) { event.preventDefault(); //prevents the default a href behaviour var url = $(this).closest('a').attr('href'); $.ajax({ url: url, method: 'POST', success: function(data) { console.log('GENIUS!'); } }); });
I know that this is not a solution for every situation where you want to call an Ajax request, but I just leave it here, and maybe someone finds this useful :)
source share