[SOLVED] Using routes in an external js file

I am currently using ajax in a twig template. To call the url from ajax I am using a route. Here is the full ajax

        $.ajax({
        url: "{{ path_for('myfundrequest') }}",
        type: 'get',
        dataType: 'json'
        }).done(function (response) {
        var len = response.length;

        fund.empty();

        for (var i = 0; i < len; i++) {
        var fundNum = response[i][0];
        var fundName = response[i][1];

        fund.append("<option value='" + fundNum + "'>" + fundNum + ' -- ' + fundName + "</option>");
        }
        fund.prepend("<option value=''>- Select A Fund -</option>").val('');
        }).fail(function (jqXHR, textStatus, error) {
        console.log("getFund: " + error);
        });
        });

If I move this to an external js file in my public folder how do I still call this the route in the url?

url: "{{ path_for('myfundrequest') }}"

Here is what my route looks like

$app->get('/fundrequest', 'PoEntryController:fund')->setName('myfundrequest');

There’s probably multiple ways to do this. One simple option could be using HTML data attributes to store the url and then pick it up with JS.

// HTML
<button class="btn" data-url="{{ path_for('route_name') }}">Do something</button>

// JS
var url = $('.btn').data('url');

I actually got a good answer on stackoverflow. @jmatthesis said

Add the urls as global variables maybe on an global object

index.twig

<!-- [..] -->
<script>
     Url = {
               myfundrequest: "{{ path_for('myfundrequest') }}"
             };
</script>

and then later use Url.myfundrequest as the url in JavaScript

$.ajax({
         url: Url.myfundrequest,
     ..

That’s indeed how I use to do it.

How do you do it now?

Sorry I meant “how I usually do it” :slight_smile: