Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Michael Galbraith
Michael Galbraith
Courses Plus Student 7,327 Points

How should I pass data from a php foreach loop to javascript?

I have a group of 13 items I have in a database. I have used a foreach loop in php to create a div that shows the image, name and a short product description. I am trying to learn javascript and wanted to try using a modal instead of each item opening its own page. However the modal opens up with either the first or last entry only and none in between.

My thought to solve this was to create a javascript array that stored the image path, product name and description and then when you clicked on the link the <a> id would correspond with the number of the javascript array to get the right info. However I am not sure how to create a dynamic javascript variable name. I can use echo to give a variable a php value for a definition but it doesn't work if I try that with the name. How would I do that? Is there a more efficient way to go about this? thanks!