Reputation: 23
I am trying to get an array produced in my php controller to pass data to javascript in a .twig file.
I am able to access all the values in a for loop in the .twig but when trying to get the value in javascript, I am only able to get the whole array by using:
var markers = {{ products|json_encode|raw }};
This produces:
var markers = [{"id":"1","name":"x","location":"San Diego"},{"id":"2","name":"y","location":"LA"}];
When trying to access specific values using a for loop within the javascript:
for (i = 0; i < markers.length; i++)
{
alert(markers[i][0])
}
Using console.log / alert I get [undefined] for markers[i][0] and [object object] if I loop through markers[i]. The length is correct.
This is my first project using .twig so I don't know if I am just missing something really obvious as I can't seem to find my problem.
Any help would be appreciated!
Upvotes: 1
Views: 395
Reputation: 1145
It appears that your issue lies in the javascript for loop.
Look here:
var markers = [{"id":"1","name":"x","location":"San Diego"},{"id":"2","name":"y","location":"LA"}];
None of the objects within your array have a property named 0
. You only have properties called id
, name
and location
.
Change your loop to something like:
for (i = 0; i < markers.length; i++)
{
alert(markers[i]['name'])
}
You should see it shows you the value of each objects name
property.
Upvotes: 1