0
I’m developing a web application with Laravel and I noticed something strange.
When passing a variable from Laravel to the HTML page two different behaviors are happening:
when calling the variable in an internal script in HTML it is recognized;
however, when calling the variable in an external script, in a Javascript file referencing it at the end of the HTML body tag, it is not recognized.
I clarify that I tested both with the echo of the Laravel Blade, as with the php opening and closing tags in the Javascript file and the variable was not recognized.
Does anyone know why this kind of behavior happens?
Below I inform a sample of the code used in Laravel:
<!DOCTYPE html>
<html lang=pt-br>
<head>
<meta charset="utf=8">
<title>Teste</title>
</head>
<body>
<div>
<img class="destaque1" src="{{ asset('images/banners/00004.jpg') }}">
</div>
<script>
var stringImagensBanners = "{{ $imagensBanners }}";
var banners = stringImagensBanners.split(",");
var bannerAtual = 0;
function trocaBanner() {
document.querySelector('.destaque1').src = banners[bannerAtual];
bannerAtual = (bannerAtual + 1);
if (bannerAtual == 5) {
bannerAtual = 0;
} return false;
}
setInterval(trocaBanner, 4000);
</script>
</body>
</html>
can post the sending code and the script that receives the variable ?
– Jefferson Mello Olynyki
Welcome to Stack Overflow! Please include a example of code that reproduces what is happening, because your question is not noticeable. See Help Center How to Ask.
– William Pereira
If I understand, what you are trying to do is not possible, because you are trying to interpret a php command inside a file. js, for php to be interpreted it needs to be inside a .php. file What you could do is put this information inside a Hidden input and then take external js with a type selector:
$('#id-input-hidden').val();
– JuniorNunes
Thanks for the guidance Juniornunes.
– Jansen Magalhães
I don’t know if I understand, but you want to use a php variable inside a js file referenced in the page?
– Douglas Carvalho
I was trying to do this because I saw it in some other fakes and I thought it worked. So, there is no way to use REST of PHP in direct Javascript, it has to be intermediated by html? I’ve seen some tutorial videos using Blade template in the . js file and was looking to clarify this issue.
– Jansen Magalhães
Yes Douglas is that.
– Jansen Magalhães