I'm using laravel for a project, I have the following problem, in the controller I have an array called escalaphonevalue that is filled, then that array was sent to the view using return and compact, in the view I need to pass that array to a script and go through it inside javascript, I pass the php array to the script as follows in the blade view:
<script>
var cont= "<?php echo $count; ?>";
for (var index1 = 0; index1 < cont; index1++) {
precioesca[index1]="<?php echo $escalafonvalor[".index1."] ?>";
alert(precioesca[index1]);
}
</script>
the array arrives like this:
array:3 [▼
0 => 13282000
1 => 4688000
2 => 2344000
]
The array passes correctly to the script, since if I give it index 0 it shows me its value and saves it in the js variable. My problem comes when I try to go through the array with the variable index1 of the javascript for, since it tells me that the variable index1 is undefined:
What can be wrong here? or how should it be done?
In this case the variable index1 is a variable in javascript, but you try to access it in php. The correct way to do it would be:
Consider that the code
PHP
is compiled and executed on the server side, insteadJS
it is compiled and executed on the client side ( usually a browser ).In other words, the code is executed first
PHP
, the result is returned to the client, and the client executesJS
.Taking this into account, if you need to iterate through
JS
information stored in a variablePHP
, what you have to do is print withPHP
said information so that it becomes visible inJS
Solution:
You can use the function
json_encode
, which allows you to convert the value of the variable to an object that youJS
can process.Example:
PS: The expression will
(array) $escalafonvalor
convert ( in the case that it was not )$escalafonvalor
into an array, thus allowing the correct iteration withJS
.You can do it in the following way using
length
, which makes it take the total length of the array and translate it into for asindex < 10
an example.I leave you an executable example so you can see it in action.
Using the information that Marcos gave me, I used it in this way, I attach my code in case it helps someone.