4

I have a javascript that requires a root directory path provided by PHP to call the JSON file.

I'm not sure if this code should be in public/js or within my template.blade.php?

If it's in public/js, then I have to specify a absolute path like below, so everytime I want to change my directory name or domain I have to change the path as well.

url: "/myBookStore/public/api/book-type/"

    <script>
    $().ready(function(){
    $("#book_type").keyup(function(){
        $.ajax({
             type: "GET",
             url: "/myBookStore/public/api/book-types/" + $("input[name=book_type]").val(),
             dataType: "json",
             success: function(json){
                //do stuff
             }
        });
    });
});
    </script>

If I put it in template.blade.php, I could use URL::to('/') to specify the base url. However It would have to be OUTSIDE of public folder, I'm not sure if it's good practice?

template.blade.php

    <script>
    $().ready(function(){
    $("#book_type").keyup(function(){
        $.ajax({
             type: "GET",
             url: {{ URL::to('/') }} + "/api/book-types/" + $("input[name=book_type]").val(),
             dataType: "json",
             success: function(json){
               //do stuff
             }
        });
    });
});
    </script>
tereško
  • 58,060
  • 25
  • 98
  • 150
Robert M. Tijerina
  • 165
  • 2
  • 4
  • 12
  • 1
    To comment on part of your question, my Javascript files are usually in the `public/assets` folder, so you can call them via `URL::asset('assets/file.js')` – Tim Lewis Jan 26 '15 at 17:19

1 Answers1

6

Simply create a

<meta name="base_url" content="{{ URL::to('/') }}">

and read the contents of this meta tag with javascript.

jQuery:

var url = $('meta[name="base_url"]').attr('content');

javascript:

var url = document.getElementsByName('base_url')[0].getAttribute('content')

This way you can have your javascript in your public js folder and still get the correct url all the time.

baao
  • 71,625
  • 17
  • 143
  • 203