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>
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.