rosedoucette / P5-Web-Dev-Kanap

Boiler plate code for project 5 of Web Developer.
0 stars 0 forks source link

parameters #1

Closed rosedoucette closed 1 year ago

rosedoucette commented 1 year ago

Hi @AccessiT3ch, I am on milestone #4-6 for this project, and I have read the recommended resource https://easyautotagging.com/javascript-get-url-parameter/ as well as googled my question, phrasing it every which way I know how. I am assuming the parameter comes from the product id inside the product.js file, but I'm not exactly sure how to make that into a url for the product.html page.

AccessiT3ch commented 1 year ago

@rosedoucette - great question! So if you look at the homepage HTML we can actually see an example of such a url on the links to the product pages. By following those links you should be taken to a product page with a url something like localhost:8000/product?id=42 wherein 42 is the product id in this case.

From the product page js, the trick is to get that id from the URL so we can make the right API call (for that individual product). We can do this in one or two steps, first we grab window.location.search which will be everything after the ? in the url as a string and then getting the ID from that.

const searchString = window.location.search; //  'id=42'
const params = new URLSearchParams(searchString); // some special object that comes with a .get() method
const productId = params.get('id'); // '42'

Hope that makes sense!