Hussain Ali
Hussain Ali

Reputation: 166

Laravel 5 External JavaScript Files_ JavaScript stack

the following JavaScript is working perfect in side the test.blad.php file but when i made external test.js file at the browser i get some thing like

http://localhost:8000/%7B%7Burl('/barcode')%7D%7D?j_barcode=112234

instead of

 http://localhost:8000/barcode?j_barcode=112234

the code in test.js file is :

$(document).ready(function(){ 
 $('#barcode').keyup(function(event){
  if(event.keyCode == 13){            
            var j_barcode = $('#barcode').val();      
   $.get("{{url('/barcode')}}", {j_barcode:j_barcode},   function(data) {   
         console.log(data) ;
        //success data                                             
         $.each(data,function(i, obj){       
            document.getElementById("item").value =obj.itemName;
            document.getElementById("itemId").value = obj.id;

            console.log(data) ;
        });
      });

      } 
  });

});

and the route.php

Route::get('/barcode'    , 'testController@getBarcode');

at last i decleared the test.js in test.blade.php as

<script  type="text/javascript" src="/hsm/js/test.js" ></script>

Upvotes: 0

Views: 564

Answers (2)

seedme
seedme

Reputation: 492

After some research, this is my solution:

Step 1. In the blade file, add a yielded section, immediately (just to keep your scripts neat) before referring to external .js file, do something like following,

@section('js_after')
<script>let dataUrl = "{{ route('subcat') }}"</script>
<!--Then external javascript file -->
<script src="{{ asset('js/pages/somescript.js ') }}"></script>
@endsection

Step 2. In your somescript.js file, you may refer and manipulate with this pre-defined variable dataUrl, such as,

var url = dataUrl+'?someParam='+id
$.get(url)

reference: https://stackoverflow.com/a/59994382/3107052

Upvotes: 0

Thomas
Thomas

Reputation: 8859

You can not use blade or php code inside files which are not interpreted by php.

The simplest way, as already suggested by @dev-null is to hardcode that url. But that generates problems when you're on a sub page like "/articles/2015" since it will then try to call "/articles/barcode".

You will have to find a way to pass the site root url to your js file. The way I always solve this is to define a global variable in my main template with all the php interpreted values required in js.

var App = {
    root: '{{ url('/barcode') }}',
    texts: {
            // some translated texts for js
    }
};

That way you can easily access it in all your js files:

$.get(App.root + '/barcode')...

Note: If you use named routes like me you will have to add each URL separately instead of just the root.

Upvotes: 1

Related Questions