Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Ajax app_dev.php in url

Tags:

ajax

symfony

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.

like image 430
someuser Avatar asked Feb 18 '23 14:02

someuser


2 Answers

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

like image 185
someuser Avatar answered Feb 27 '23 07:02

someuser


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

like image 40
SirDerpington Avatar answered Feb 27 '23 06:02

SirDerpington