Symfony2 Ajax app_dev.php in url

Just started working in Symfony2 and really loved it after a long developer of ZF1.

It will start adding some Ajax features to the site tonight, and I'm a little confused about the following.

in my ajax call, for example:

$.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 in the url so that it works in a dev environment. Isn't there a better way to do this? Does this mean when I change the project to a production environment, do I need to search and replace all instances of / app _dev.php ?? I hope I completely missed something simple.

+4
source share
3 answers

I ended up using jsrouting-bundle

After installation, I can 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 the route defined in routing.yml, for example:

 urlgetter: pattern: /ajax/urlgetter defaults: { _controller: MyAjaxBundle:SomeController:urlgetter } options: expose: true 

Note that the expose: true parameter must be set in order for the route to work with jsrouting-bundle

+4
source

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 :)

+3
source

Since this jQuery ajax function is placed on the branch side and the URL points to your application, you can insert a routing route

 $.ajax({ url: '{{ path("your_ajax_routing") }}', data: "url="+urlinput, dataType: 'html', timeout: 5000, success: function(data, status){ // DO Stuff here } }); 
+1
source

All Articles