Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Michael Galbraith
PLUS
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!