Click here to Skip to main content
15,885,179 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I need help with the js code, the information in the json file is not correctly linking to the js code. I want to put information in a JSON file to display on my website, arrange it in a specific way, and call it up by clicking on one of the HTML page elements. The idea is a restaurant menu, and when you click on one of the main items, for example, a new menu will appear in which the proposed dishes made of chicken will be included. The solution I reached is to design the main page from the main elements, but the information in the JSON file is not called correctly. Please help me in this matter.

What I have tried:

HTML
<pre><!DOCTYPE html>
<html  lang="en">

<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="anas_axam1.css">
    <!--<meta charset="UTF-8"> -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>anas_axam1</title>
    <style>

    </style>
</head>

<body>
    <header>
        <h1> anas  menu</h1>
    </header>
    <div class="container" id="details" >
        <section class="item col-lg-4 col-md-5 col-s-12 item ">
            <div class="title1"> chicken</div>
            <div class="section-title_a"> 7 jd </div>
            <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Natus, nam amet laboriosam repellat tempore,
                sunt magnam deserunt officia cum a corporis! Beatae eius corporis quasi magnam excepturi repudiandae
                laboriosam ex?</p>
        </section>
        <section class="item col-lg-4 col-md-5 col-s-12 item">
            <div class="title2">beef </div>
            <div class="section-title_a"> 9 jd </div>

            <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Natus, nam amet laboriosam repellat tempore,
            sunt magnam deserunt officia cum a corporis! Beatae eius corporis quasi magnam excepturi repudiandae
            laboriosam ex?</p>
        </section>
        <section class="item col-lg-4 col-md-10 col-s-12 item ">
            <div class="title3">suchi</div>
            <div class="section-title_a"> 8 jd </div>

            <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Natus, nam amet laboriosam repellat tempore,
            sunt magnam deserunt officia cum a corporis! Beatae eius corporis quasi magnam excepturi repudiandae
            laboriosam ex?</p>
        </section>
    </div>
<script type="text/javascript" src="anas_exam1.js"></script>

</body>

</html>


HTML
<pre>


<body>

    <div class="item" id="details" onclick="loadItem();">
      <section class="item col-lg-4 col-md-5 col-s-12">
        <div class="title1"> {{name}}</div>
        <p>{{description}}</p>
      </section>
      
 

</body>

</html>



CSS
body {
    font-family: Arial, sans-serif;

}
header {
    background-color: #f0f0f0;
    padding: 20px;
    text-align: center;
}
.container {
  
    background-color: #f5f5f5;
    padding: 20px;
    box-sizing: border-box;
    
}
.container :hover {
    background-color: #a94646;
}
section {
    padding: 20px;
     box-sizing: border-box;
    background-color: gray;
    border: 2px solid #000;
    position: relative;

}
section :hover { background-color: #a94646;}
.title1 {
    position: absolute;

    top: 0;
    right: 0;
    background-color: #a94646; 
    color: #000; 
    padding: 5px 10px;
    font-size: 25% larger;
    font-weight: bold;
    border: 1px solid #000;
    border-radius: 10px;
    font-size: larger;
}
.section-title_a {
    position: absolute;

    bottom: 0;
    left: 0; 
    background-color: #a9469e;
    color: #000;
    padding: 5px 10px;
    font-size: 25% larger;
    font-weight: bold;
    border: 1px solid #000;
    border-radius: 10px;
    margin-left: 5px;
}

.title2 {
    position: absolute;
    top: 0;
    right: 0;
    background-color: #35b34e;
    color: #000;
    padding: 5px 10px;
    font-size: 25% larger;
    font-weight: bold;
    border: 1px solid #000;
        border-radius: 10px;
            font-size: larger;
}
.title3 {
    position: absolute;
    top: 0;
    right: 0;
    background-color: #b37835; 
    color: #000; 
    padding: 5px 10px;
    font-size: 25% larger;
    font-weight: bold;
    border: 1px solid #000;
        border-radius: 10px;
            font-size: larger;
}
h1 {
    font-size: 175% larger;
    margin-bottom: 20px;
}
h2 {
    font-size: 125% larger;
    margin: 0;
}
p {
    font-size: 100%;
    margin: 10px 0;
    
}




@media (min-width: 1200px){
    .container,.section,.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,
    .col-lg-10,.col-lg-11,.col-lg-12{
    
        float: left;
        margin: 0;


        
    }
    .col-lg-1{
        width: 8.33%;
    }
    .col-lg-2{
        width: 16.66%;
    }
    .col-lg-3{
        width: 25%;
    }
    .col-lg-4{
        width: 31%;
    }
    .col-lg-5{
        width: 41.66%;
    }
    .col-lg-6{
        width: 50%;
    }
    .col-lg-7{
        width: 58.33%;
    }
    .col-lg-8{
        width: 66.66%;
    }
    .col-lg-9{
        width: 75%;
    }
    .col-lg-10{
        width: 83.33%;
    }
    .col-lg-11{
        width: 91.66%;
    }
    .col-lg-12{
        width: 100%;
    }
}
@media (min-width: 850px) and (max-width: 1199px){
    .container, .section, .col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,
    .col-md-10,.col-md-11,.col-md-12{
        float: left;
       }
    .col-md-1{
        width: 8.33%;
    }
    .col-md-2{
        width: 16.66%;
    }
    .col-md-3{
        width: 25%;
    }
    .col-md-4{
        width: 33.33%;
    }
    .col-md-5{
        width: 41.66%;
    }
    .col-md-6{
        width: 50%;
    }
    .col-md-7{
        width: 58.33%;
    }
    .col-md-8{
        width: 66.66%;
    }
    .col-md-9{
        width: 75%;
    }
    .col-md-10{
        width: 83.3%;
        margin-right: 5px;
        margin-top: 15px;
    }
    .col-md-11{
        width: 91.66%;
    }
    .col-md-12{
        width: 100%;
    }
}		
 @media (max-width: 849px) {

     .container,
     .section,
     .col-s-1,
     .col-s-2,
     .col-s-3,
     .col-s-4,
     .col-s-5,
     .col-s-6,
     .col-s-7,
     .col-s-8,
     .col-s-9,
     .col-s-10,
     .col-s-11,
     .col-s-12 {
         float: left;
        margin-right: 5px;
            margin-top: 10px;
            margin-bottom: 10px;
     }

     .col-s-1 {
         width: 8.33%;
     }

     .col-s-2 {
         width: 16.66%;
     }

     .col-s-3 {
         width: 25%;
     }

     .col-s-4 {
         width: 33.33%;
     }

     .col-s-5 {
         width: 41.66%;
     }

     .col-s-6 {
         width: 50%;
     }

     .col-s-7 {
         width: 58.33%;
     }

     .col-s-8 {
         width: 66.66%;
     }

     .col-s-9 {
         width: 75%;
     }

     .col-s-10 {
         width: 83.3%;
         margin-right: 5px;
         margin-top: 15px;
        margin-bottom: 15px;

     }

     .col-s-11 {
         width: 91.66%;
     }

     .col-s-12 {
         width: 100%;
     }
 }


JavaScript
<pre>document.addEventListener('DOMContentLoaded', function () {
  const itemElements = document.querySelectorAll('section');

  itemElements.forEach(item => {
    item.addEventListener('mouseover', () => {
      document.body.style.cursor = 'pointer';
    });

    item.addEventListener('mouseout', () => {
      document.body.style.cursor = 'default';
    });
  });
});


document.addEventListener("DOMContentLoaded", function (event) {
  document.querySelector("#details").addEventListener("click", function () {
    //Call server to get the entriy and the items
    var xttp = new XMLHttpRequest();
    xttp.onreadystatechange = function () {
      if ((this.readyState == 4) && (this.status == 200)) {
        item = this.responseText;
        var xttp = new XMLHttpRequest();
        xttp.onreadystatechange = function () {
          if ((this.readyState == 4) && (this.status == 200)) {
            var entry = JSON.parse(this.responseText);
            for (let i = 0; i < entry.length; i++) {
              let div = document.createElement("div");
              let reponame = document.createTextNode(entry[i].name);
              div.appendChild(reponame);
              document.body.appendChild(div);

            }
            // item = item.replace(new RegExp("{{name}}", "g"), entry.name);
            // item = item.replace(new RegExp("{{description}}", "g"), entry.description);

            document.querySelector("#details").innerHTML = document.querySelector("#details").innerHTML + item;
          }
        };
        xttp.open("GET", "/chicken.json", true);
        xttp.send() 

        xttp.send(null);//for POST only
      }
    };
    xttp.open("GET", "item.html", true);
    xttp.send(null);//for POST only
  });

});

function loadItem() {
  //Call server to get the entriy and the items
  var item = null;
  var xttp = new XMLHttpRequest();
  xttp.onreadystatechange = function () {
    if ((this.readyState == 4) && (this.status == 200)) {
      item = this.responseText;
      var xttp = new XMLHttpRequest();
      xttp.onreadystatechange = function () {
        if ((this.readyState == 4) && (this.status == 200)) {
          var entry = JSON.parse(this.responseText);
          item = item.replace(new RegExp("{{name}}", "g"), entry.name);
          item = item.replace(new RegExp("{{description}}", "g"), entry.description);

          document.querySelector("#details").innerHTML = document.querySelector("#details").innerHTML + item;
        }
      };
      xttp.open("GET", "/chicken.json", true);
      xttp.send(null);//for POST only
    }
  };
  xttp.open("GET", "/item.html", true);
  xttp.send(null);//for POST only
}


JavaScript
[
    {"name": "Fried","description": "Fried chiken is very deleciuos and very light on stomac"},
    {"name": "boiled","description": "Boiled chiken is very healthy however it is not that tatsty."},
    {"name": "Grilled","description":"On top of a coal fire that is very hot thiskind is cooked and added to it a hot spices"},
    {"name": "Alfredo","description": "This is the easiest, creamiest chicken alfredo you will ever make."},
    {"name": "Lemon Pepper Chicken","description": "This lemon pepper chicken makes chicken exciting again."},
    {"name": "Roast","description": "You need this classic recipe in your arsenal."},
    {"name": "Biryani","description":"Chicken biryani is such an easy anddelicious dinner. Served over fluffy white rice, its hard to resist."},
    {"name": "Tamale Pie","description": "A layer of cornbread topped with cheesy shredded chicken."}

]
Posted
Updated 11-Aug-23 22:59pm
v2

1 solution

First things first, in future, please do not just dump all of your code and expect to get a solution. By doing this shows me that you do not really understand the code (copied and pasted from somewhere else maybe?) and hope someone will work through a gazillion lines to try and help you.

You were on the right track with your Javascript code, I modified it slightly by adding an 'event listener' to each menu item element with the class 'item' to call the 'loadItem' function when clicked. The 'loadItem' function now loads the menu items from the JSON file and creates the HTML dynamically to display the menu items. I have also changed the structure of the generated HTML to use
elements with classes for styling. Your code will look something like this -
JavaScript
document.addEventListener('DOMContentLoaded', function () {
  const itemElements = document.querySelectorAll('.item');

  itemElements.forEach(item => {
    item.addEventListener('mouseover', () => {
      document.body.style.cursor = 'pointer';
    });

    item.addEventListener('mouseout', () => {
      document.body.style.cursor = 'default';
    });

    item.addEventListener('click', loadItem);
  });
});

function loadItem() {
  //Make a call to your server to get the entry and the items...
  var xttp = new XMLHttpRequest();
  xttp.onreadystatechange = function () {
    if ((this.readyState == 4) && (this.status == 200)) {
      var entry = JSON.parse(this.responseText);
      var menuHTML = '';

      for (let i = 0; i < entry.length; i++) {
        menuHTML += `
          <div class="menu-item">
            <div class="menu-item-title">${entry[i].name}</div>
            <p>${entry[i].description}</p>
          </div>
        `;
      }

      document.querySelector("#details").innerHTML = menuHTML;
    }
  };
  xttp.open("GET", "/chicken.json", true);
  xttp.send();
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900