Search code examples
javascripthtmljson

How to display an image in html via a json file using javascript


Hy everyone, I'm new to the forum and have a question about using a json file... I almost have what I would like to have except an image that won't show on my page, instead the path to the image is printed out... enter image description here

I'm kinda new to this json thing, so please can somebody help me figure it out? The json file would be like a little database just for the thumbnails of the blog posts, so I don't have to hard code them. On the print screen i have already a little bit what I want, don't mind style I will take care of that after i understand this problem...

This is the jason file

[
  {
    "postid": "4",
    "title": "More coming soon",
    "text": "Soon I will add more recipes, this is just the start of a blog full of content! Come back regulary",
    "img": "https://pbs.twimg.com/profile_images/735509975649378305/B81JwLT7.jpg",
    "url": "#"
  },
  {
    "postid": "3",
    "title": "Pizza",
    "text": "The Italian classic, so many different styles of it. Try this recipe at home, for a crusty tastfull pizza!",
    "img": "https://pbs.twimg.com/profile_images/735509975649378305/B81JwLT7.jpg",
    "url": "#"
  },
  {
    "postid": "2",
    "title": "Madeleines",
    "text": "French classic scallop shape little cakes, perfect with a cup of coffee. You can make them easy at home!",
    "img": "../assets/images/recipes/Madeleines.png",
    "url": "#"
  },
  {
    "postid": "1",
    "title": "Moelleux",
    "text": "A special one for the chocolate lovers! The best chocolate dessert is very easy to make, give it a try...",
    "img": "../assets/images/recipes/Moelleux.png",
    "url": "#"
  }
]

This is the html part

  <!--  Jason test  -->
  <div class="search-wrapper">
    <label for="search">Search Users</label>
    <input type="search" id="search" data-search>
  </div>
  <div class="user-cards" data-post-cards-container></div>
  <template data-post-template>
    <div class="card">
      <div class="header" data-header></div>
      <div class="body" data-body></div>
      <div class="photo" data-photo></div>
    </div>
  </template>
  <!--  End Jason test  -->

And this is the javascript part

const postCardTemplate = document.querySelector("[data-post-template]")
const postCardContainer = document.querySelector("[data-post-cards-container]")
const searchInput = document.querySelector("[data-search]")

let posts = []

searchInput.addEventListener("input", e => {
  const value = e.target.value.toLowerCase()
  posts.forEach(post => {
    const isVisible =
      post.title.toLowerCase().includes(value)
    post.element.classList.toggle("hide", !isVisible)
  })
})

fetch("../jsn/posts-main.json")
  .then(res => res.json())
  .then(data => {
    posts = data.map(post => {
      const card = postCardTemplate.content.cloneNode(true).children[0]
      const header = card.querySelector("[data-header]")
      const body = card.querySelector("[data-body]")
      const img = card.querySelector("[data-photo]")
      header.textContent = post.title
      body.textContent = post.text
      img.textContent = post.img
      postCardContainer.append(card)
      return { title: post.title, element: card }
    })
})

Thank you already

Followed a tutorial on youtube and already search a lot for a solution but I can't figure it out


Solution

  • The issue is because you're just appending the URL to the image as text within the parent div.

    To fix the problem you need to create an img element and set the information from the fetch request as the src of that img.

    Here's a simplified example:

    // mock AJAX data:
    const data = [{postid:"4",title:"More coming soon",text:"Soon I will add more recipes, this is just the start of a blog full of content! Come back regulary",img:"https://pbs.twimg.com/profile_images/735509975649378305/B81JwLT7.jpg",url:"#"},{postid:"3",title:"Pizza",text:"The Italian classic, so many different styles of it. Try this recipe at home, for a crusty tastfull pizza!",img:"https://pbs.twimg.com/profile_images/735509975649378305/B81JwLT7.jpg",url:"#"},{postid:"2",title:"Madeleines",text:"French classic scallop shape little cakes, perfect with a cup of coffee. You can make them easy at home!",img:"../assets/images/recipes/Madeleines.png",url:"#"},{postid:"1",title:"Moelleux",text:"A special one for the chocolate lovers! The best chocolate dessert is very easy to make, give it a try...",img:"../assets/images/recipes/Moelleux.png",url:"#"}];
    
    
    const postCardTemplate = document.querySelector("[data-post-template]")
    const postCardContainer = document.querySelector("[data-post-cards-container]")
    
    // within fetch handler
    let posts = []
    
    posts = data.map(post => {
      const card = postCardTemplate.content.cloneNode(true).children[0]
      const header = card.querySelector("[data-header]")
      const body = card.querySelector("[data-body]")
      const img = card.querySelector("[data-photo]")
      
      header.textContent = post.title
      body.textContent = post.text
      
      const imgContent = document.createElement('img');
      imgContent.src = post.img;
      img.appendChild(imgContent);
      
      postCardContainer.append(card)
      return {
        title: post.title,
        element: card
      }
    })
    <div class="search-wrapper">
      <label for="search">Search Users</label>
      <input type="search" id="search" data-search>
    </div>
    <div class="user-cards" data-post-cards-container></div>
    <template data-post-template>
        <div class="card">
          <div class="header" data-header></div>
          <div class="body" data-body></div>
          <div class="photo" data-photo></div>
        </div>
      </template>