Rafiq
Rafiq

Reputation: 11445

Laravel Passing route to js

I have a separate js file into laravel public folder, I have decleard my route into web.php, I can use them in blade file but getting error while try to use them in that js file.

$.ajax({
   //url:"http://127.0.0.1:8000/cats/fetch",
    url:"{{route('cats.fetch')}}",
    method:"POST",
    data:{select:select, value:value, _token:_token, dependent:dependent},
    success:function(result)
    {
      $('#'+dependent).html(result);
    }

})

but when I use hard coded url then its work for instance url:"cats/fetch". How can I make it configurable not hard coded into js file

Upvotes: 1

Views: 978

Answers (1)

Tim Lewis
Tim Lewis

Reputation: 29258

url:"{{route('cats.fetch')}}", is not valid .js syntax. You're correct that you can use it in .blade.php, but in an external .js file, you need to assign it to a variable first:

<script type="text/javascript">
  let url = "{{ route('cats.fetch') }}";
</script>
<script src="path/to/file.js" type="text/javascript"/>

Then, in file.js, reference the variable:

...
url: url,
...

Upvotes: 1

Related Questions