Just starting out in Symfony2 and really loving it after being a long time ZF1 developer.
Started to add some Ajax functionality to a site tonight and am a bit confused about the following.
in my ajax call eg:
$.ajax({
url: '/app_dev.php/ajax/urlgetter',
data: "url="+urlinput,
dataType: 'html',
timeout: 5000,
success: function(data, status){
// DO Stuff here
}
});
I had to add /app_dev.php to the url to make it work in dev environment. Is there not a better way of doing this? Does this mean when I change the project to a production environment I need to search and replace all instances of /app_dev.php?? Hopefully I have totally missed something simple.
I ended up using the jsrouting-bundle
Once installed I could simply do the following:
$.ajax({
url: Routing.generate('urlgetter'),
data: "url="+urlinput,
dataType: 'html',
timeout: 5000,
success: function(data, status){
// DO Stuff here
}
});
where urlgetter is a route defined in routing.yml like:
urlgetter:
pattern: /ajax/urlgetter
defaults: { _controller: MyAjaxBundle:SomeController:urlgetter }
options:
expose: true
notice the expose: true option has to be set for the route to work with jsrouting-bundle
I guess this question is already kind of old but I came across the same problem.
Its not any "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 a structure like that:
...
<a href="{{ path('myRoute') }}"> //results in e.g http://localhost/app_dev.php/myRoute
<div id="clickMe">Click</div>
</a>
Now if someone clicks the div, I do the following in my .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 trigger an Ajax request but I just leave this here and perhaps somebody thinks it's useful :)
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