I'm looking for help I'm trying to get some data of json file from an api that I'm using for student project ( I'm very beginner on API stuff).
I'm at the beginning of the project and they asked me to get all of the json file data on the homepage with all informations associated with :
Those are the data that I extract for the API
It's works fine and when the user click on one of the item it's show the same information but only the for the one clicked and this is where I'm stuck.
When I click on an item each of them have an id related to a link showing their own id :
The small code use through a loop to get all items id
So I create another js file for the product page where I have to implement them only with Javascript Vanilla and this is what I've tried :
// API REQUEST
const connection = fetch ('http://localhost:3000/api/products')
/* *********CONNECION*********** */
connection.then((response) => {
if(response.ok){
return response.json();
}
else{
console.log('Connection failed');
}
})
/* ********END DE CONNEXION*********** */
.then((jsonArray) => {
function JsDemo(myData){
// TARGETING ON HTML SELECTORS
const imgOfTheActualProduct = document.querySelector(".item__img > img");
const titleOfTheActualProduct = document.querySelector(".item__content__titlePrice > #title");
const priceOfTheActualProduct = document.querySelector(" .item__content__titlePrice #price");
const colorOfTheActualProduct = document.querySelector("#colors");
const descriptionOfTheActualProduct = document.querySelector('.item__content__description #description');
// Loop to get json elements
for(let i = 0 ; i < myData.length; i ){
imgOfTheActualProduct.src=`${myData[i].imageUrl}`;
titleOfTheActualProduct.innerHTML=`${myData[i].name}`;
priceOfTheActualProduct.innerHTML=`${myData[i].price}`;
descriptionOfTheActualProduct.innerHTML=`${myData[i].description}`
// colorOfTheActualProduct.innerHTML=`${myData[i].colors}`;
}
}
JsDemo(jsonArray);
})
The code above work(only with the api not here :) ) but it's showing only the last data of the json file and I retrieve the same thing when I'm selecting all of the item on homepage...
Just to get an idea of what I'm talking about for the JSON part :
[
{
"colors": ["Blue", "White", "Black"],
"_id": "107fb5b75607497b96722bda5b504926",
"name": "Kanap Sinopé",
"price": 1849,
"imageUrl": "http://localhost:3000/images/kanap01.jpeg",
"description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
"altTxt": "Photo d'un canapé bleu, deux places"
},
{
"colors": ["Black/Yellow", "Black/Red"],
"_id": "415b7cacb65d43b2b5c1ff70f3393ad1",
"name": "Kanap Cyllène",
"price": 4499,
"imageUrl": "http://localhost:3000/images/kanap02.jpeg",
"description": "Morbi nec erat aliquam, sagittis urna non, laoreet justo. Etiam sit amet interdum diam, at accumsan lectus.",
"altTxt": "Photo d'un canapé jaune et noir, quattre places"
},
{
"colors": ["Green", "Red", "Orange"],
"_id": "055743915a544fde83cfdfc904935ee7",
"name": "Kanap Calycé",
"price": 3199,
"imageUrl": "http://localhost:3000/images/kanap03.jpeg",
"description": "Pellentesque fermentum arcu venenatis ex sagittis accumsan. Vivamus lacinia fermentum tortor.Mauris imperdiet tellus ante.",
"altTxt": "Photo d'un canapé d'angle, vert, trois places"
},
{
"colors": ["Pink", "White"],
"_id": "a557292fe5814ea2b15c6ef4bd73ed83",
"name": "Kanap Autonoé",
"price": 1499,
"imageUrl": "http://localhost:3000/images/kanap04.jpeg",
"description": "Donec mattis nisl tortor, nec blandit sapien fermentum at. Proin hendrerit efficitur fringilla. Lorem ipsum dolor sit amet.",
"altTxt": "Photo d'un canapé rose, une à deux place"
},
{
"colors": ["Grey", "Purple", "Blue"],
"_id": "8906dfda133f4c20a9d0e34f18adcf06",
"name": "Kanap Eurydomé",
"price": 2249,
"imageUrl": "http://localhost:3000/images/kanap05.jpeg",
"description": "Ut laoreet vulputate neque in commodo. Suspendisse maximus quis erat in sagittis. Donec hendrerit purus at congue aliquam.",
"altTxt": "Photo d'un canapé gris, trois places"
},
{
"colors": ["Grey", "Navy"],
"_id": "77711f0e466b4ddf953f677d30b0efc9",
"name": "Kanap Hélicé",
"price": 999,
"imageUrl": "http://localhost:3000/images/kanap06.jpeg",
"description": "Curabitur vel augue sit amet arcu aliquet interdum. Integer vel quam mi. Morbi nec vehicula mi, sit amet vestibulum.",
"altTxt": "Photo d'un canapé gris, deux places"
},
{
"colors": ["Red", "Silver"],
"_id": "034707184e8e4eefb46400b5a3774b5f",
"name": "Kanap Thyoné",
"price": 1999,
"imageUrl": "http://localhost:3000/images/kanap07.jpeg",
"description": "EMauris imperdiet tellus ante, sit amet pretium turpis molestie eu. Vestibulum et egestas eros. Vestibulum non lacus orci.",
"altTxt": "Photo d'un canapé rouge, deux places"
},
{
"colors": ["Pink", "Brown", "Yellow", "White"],
"_id": "a6ec5b49bd164d7fbe10f37b6363f9fb",
"name": "Kanap orthosie",
"price": 3999,
"imageUrl": "http://localhost:3000/images/kanap08.jpeg",
"description": "Mauris molestie laoreet finibus. Aenean scelerisque convallis lacus at dapibus. Morbi imperdiet enim metus rhoncus.",
"altTxt": "Photo d'un canapé rose, trois places"
}
]
To be honest I don't know what to I'm not looking for the solution just an hint.
I looked for URL search parameters on mdn but I don't really understand on what it's could be useful here because I already know that each Id is correctly linked ( Or maybe I'm wrong ?!)
Sorry its little long.
Thanks for reading !
So here I moved the query selector within the loop
for(let i = 0; i < myData.length; i ){
const imgOfTheActualProduct = document.querySelector(".item__img > img");
const titleOfTheActualProduct = document.querySelector(".item__content__titlePrice > #title");
const priceOfTheActualProduct = document.querySelector(" .item__content__titlePrice #price");
// const colorOfTheActualProduct = document.querySelector("#colors");
const descriptionOfTheActualProduct = document.querySelector('.item__content__description #description');
imgOfTheActualProduct.src=`${myData[i].imageUrl}`;
titleOfTheActualProduct.innerHTML=`${myData[i].name}`;
priceOfTheActualProduct.innerHTML=`${myData[i].price}`;
descriptionOfTheActualProduct.innerHTML=`${myData[i].description}`
// colorOfTheActualProduct.innerHTML=`${myData[i].colors}`;
}
<div >
<img src="../images/logo.png" alt="Photographie d'un canapé">
</div>
<div >
<div >
<h1 id="title"><!-- Nom du produit --></h1>
<p>Prix : <span id="price"><!-- 42 --></span>€</p>
</div>
<div >
<p >Description :</p>
<p id="description"><!-- Dis enim malesuada risus sapien gravida nulla nisl arcu. --></p>
</div>
Edit :
So I've done what you wrote and it's the opposite this time it's the first image that is displayed when you click on each link and the console return me that :
I try to see if I wrote it wrong and when I removed the variable showed in the console the same error displayed for each variable below of imgOfTheActualProduct.
If I could modify the html I would really but I don't have the right to did it, all I have to is built the rest of the project only with Javascript Vanilla.
I'm wondering if I could do what I need with URLsearchparamaters , I'm gonna do some research on it
CodePudding user response:
The JsDemo function has the query selector logic invoked only once outside the loop. The loop then goes through the array & overwrites all the properties in every iteration. So,at the end of the loop,the last element of the array will be used to populate values. You could move the query selector logic within the loop if your aim is to populate every card. You would have to use the index i.e. the i variable for that purpose.
The Html doesn't have an attribute marking the index of the card.If you want to keep the same html,you can use document.querySelectorAll() with the index i like below.
const imgOfTheActualProduct = document.querySelectorAll(".item__img > img")[i];
const titleOfTheActualProduct = document.querySelectorAll(".item__content__titlePrice > #title")[i];
const priceOfTheActualProduct = document.querySelectorAll(" .item__content__titlePrice #price")[i];
// const colorOfTheActualProduct = document.querySelectorAll("#colors")[i];
const descriptionOfTheActualProduct = document.querySelectorAll('.item__content__description #description')[i];