user1899829
user1899829

Reputation: 407

How can I put in a laravel route in a js file

I have my javascript code in a js file that I include in my main layout. I want to call ajax, to a specific named route. Becuase it is a js file, the blade syntax can't be run from there. I tried writing out the url, but the url changes depending on the route that is calling the ajax, so it's not pointing to the correct folder. I'd rather use a names route. Any other suggestions?

Upvotes: 1

Views: 2181

Answers (2)

Mojtaba
Mojtaba

Reputation: 5004

In your view file, define a global JavaScript variable:

<script>
var globalRouteName = "{{ $route }}";
</script>

And now, in your js file, simply use globalRoutName as variable.

Upvotes: 0

Adam Kelso
Adam Kelso

Reputation: 391

Have you considered writing out all the named routes you'll need into the view? Perhaps make a hash of routes and just make the ajax call to the one you need at the time. Something like:

var routes = {
    'first': '{{ route('first') }}',
    'second': '{{ route('second') }}',
    // ....
};

// Somewhere later in code
$http.get(routes.second).then(function(result) {
    // do something
});

Upvotes: 3

Related Questions