Laravel 5 External JavaScript Files_ JavaScript stack - javascript

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>

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.

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

Related

Django: How to pass python variable value to javascript file?

I've a function in views.py which returns latitude and longitude:
return render(request, 'map.html', {'lat_lng':lat_lng})
and I am able to access it in html file as {{ lat_lng }} but when I try to use lat_lng in separate js file then I'm not able to access it.
I tried all below stack answers but none worked for me:
Django Template Variables and Javascript
Passing django variables to javascript
How to use Django variable in JavaScript file?
Passing Python Data to JavaScript via Django
You can take advantage of json_script template tag. In your template do this
{{ lat_lng|json_script:"lat_lng" }}
Then in your javascript file you can access this variable like
const lat_lng = JSON.parse(document.getElementById("lat_lng").textContent);
One simple way to do it is to append the following snippet at the top of your template html file(the one that imports your javascript file):
<script type="text/javascript">
const LAT_LNG = "{{ lat_lng }}"; // Or pass it through a function
</script>
when I try to use lat_lng in separate js file then I'm not able to access it.
You can't use a django template variable in a static file. The static files will be returned in a way that bypasses Django's typical request processing.
Instead, set the variables on data-* attributes on an known HTML element, then get the element, access the attribute and use the value that way.
Be sure when that getting the variable in a script tag is before including the separate js file
Exmple :
<script type="text/javascript">
var variable = "{{myV}}";
</script>
<script type="text/javascript" src="myJsFile.js"></script>

How can I access Laravel Helper from Javascript?

I have a Laravel web app and want to access my Laravel Helper from any .js file.
In normally I accessed helper from script in blade.php file like this:-
<script>
function getSiteSettings() {
return JSON.parse('<?php echo json_encode(Helper::getSettings()) ?>');
}
</script>
But I want to access this from my script.js file. Is it possible?
I have tried with localStorage and get it very easily but problem is, in site settings have some secured data.
And if possible to hide localStorage data then my problem will be solved.
I found the answer. Basically, there is no direct way to write PHP code in the .js file. Here is 3 short way to get PHP/Laravel variable or Laravel Helper.
Solution 1. Call an ajax and get the return the value from js and use it as needed.
$(function() {
// ajax call
});
Solution 2. Any Laravel Helper/Var can be accessible from a blade file, like this:
<script>
let name = "{{ \Helper::get_name() }}";
</script>
and use this name anywhere in js.
Solution 3. The last and best way which I have been using is:
Add the external script in the blade and add a getter and setter method into the script so that you can set the value from the blade file inside the js.
// in external/script.js script
var GetLaravelHelper = function () {
let options = {
name_from_laravel : ''
}
return {
init: function(){
// code for on load
},
set_options: function(data){
Object.assign( options, data );
},
get_options: function(){
return options;
}
}
}();
window.GetLaravelHelper = GetLaravelHelper; // You can get acces this GetLaravelHelper into balde file where you imort this js
document.onload(function(){
GetLaravelHelper.init();
})
Then in blade, you can set any value into the Object like this:
<script src="external/script.js"></script>
<script>
GetLaravelHelper.set_options({
name_from_laravel: "{{ config('app.name') }}", // or anything from laravel/php
})
</script>
Hope it will help you a lot. Happy Coding <3
I think your best bet is to do what you're doing right now.
Or, Create a resource endpoint that can return JSON of these settings on page load in your script.js file:
// script.js
document.addEventListener("DOMContentLoaded", function() {
// make an ajax request here and load your setting in a js variable
});
// if using jquery
$(function() {
// make an $.ajax request here and load your setting in a js
})
The easiest solution will be call an api using Ajax or Axios(is using vue) inside the getSiteSettings function and in the response of the api you return the data.

How to access env veriables in js file in laravel

I intigrate Stripe Api for testing how can i set public key in env.
How to use in strip public key in js
Public key:
STRIPE_KEY=pk_test_IS796OfBm2ZFLfvBbwsXHJLK00fE6oqivk
and js file where use this veriable:
var stripe = Stripe({{ env('STRIPE_KEY') }});
{{ }} is a .blade syntax control, and cannot be used in .js files.
If you have a <script> element inside a .blade.php file, then it will work, but otherwise you'll need to load the file into JS before including the .js file, or get the value via an ajax call.
For example, loading the variable to js before including the .js script:
example.blade.php:
<script type="text/javascript">
let stripe_key = '{{ env("STRIPE_KEY") }}';
</script>
<script src="{{ asset('js/stripe.js') }}"></script>

Django accessing non-static files from static files

I have a javascript static file within which I would like to specify a source url to a non-static json file. The below doesn't seem to work (the root directory here is the root directory of the django project):
source: {url: "users/username1/nonstatic.json"}
It works if I explicitly (and non-ideally) specify an absolute static json url:
source: {url: "static/default_GCMS.json"}
Am wondering what's the correct way of calling a non-static file from a static one (.js in this case).
So you want to call a django view from a static JS file. This is a rather common problem - to solve it you need to mix and match django template logic with static JS.
One easy solution would be to assign the URL of the view you'd like to call to a global JS variable in your django template before including your static JS file and then use that variable. So, your django template would be something like this
<script>
var g_djangoViewUrl = '{% url "my_django_view_url %}';
// Notice that g_djangoViewUrl is global (assigned to your window object) so will be visible from other JS files
</script>
<script src='the_js_file_that_will_use_the_url.js'></script>
The above has the problem that you'll need to remember to define the urls that will be needed before including your js files. A more structured and permanent solution would be to create a django-view whose only purpose would be to output a global object that would contain all the urls you are going to use from other JS files. So, you'll have something like this in your template
<script src='{% url "my_url_creating_view" %}'></script>
<script src='the_js_file_that_will_use_the_url.js'></script>
The my_url_creating_view should have a correct content type (application/javascript) and should just return a object like this:
var g_URLS = {
djangoView1: {% url "django_view_1" %},
djangoView2: {% url "django_view_2" %}
}
etc

getJSON url method doesn't work when called from external javascript

This is a complex issue and I am wondering if this is more related with JSONP (JSON + padding) or not.
So there is a file called example.php
<script src="jquery.js"</script>
<script src="example.js" onload="getInfo();"></script>
<p class="one"></p>
Now in the example.js file, I use the getJSON method:
$(document).ready(function() {
function getInfo() {
$.getJSON("URL", function(data) {
var name = [parses through the json data];
$("p.one").html(name);
This does't work however if it is not involving an external JSON file it works.
Here is a previous question that was answered: Best way to access external JavaScript file and place contents in div?
Curious to know if anyone else has faced this problem and I haven't been able to find anything by Google or on StackOverflow on this.
Change your script calling syntax as follows. Remove onload attribue. There is no attribute onload for script tag
<script src="example.js"></script>
And, your example.js file look like this. You may call the getInfo() method in that file also
$(document).ready(function() {
function getInfo() {
$.getJSON("URL", function(data) {
var name = [parses through the json data];
$("p.one").html(name);
});
}
getInfo();
});

Categories

Resources