0

There are separate categories on my page. But it is not possible to exclude all categories.

index.html:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Display JSON Data by Category</title>
</head>
<body>
  <label for="category-select">Filter by Category:</label>
  <select id="category-select">
    <option value="all">All</option>
    <option value="fruits">Fruits</option>
    <option value="vegetables">Vegetables</option>
    <option value="dairy">Dairy</option>
  </select>

  <div id="category-container"></div>

  <script src="app.js"></script>
</body>
</html>

app.js:

// Wait for the DOM to finish loading
document.addEventListener("DOMContentLoaded", function() {

  // Get references to the category select element and category container element
  var categorySelect = document.getElementById("category-select");
  var categoryContainer = document.getElementById("category-container");

  // Attach an event listener to the category select element
  categorySelect.addEventListener("change", function() {
    // Get the selected category
    var category = categorySelect.value;

    // Send an AJAX request to the server to get the data for the selected category
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        // Parse the JSON response
        var data = JSON.parse(xhr.responseText);

        // Filter the data by the selected category
        if (category) {
          data = data.filter(function(item) {
            return item.category == category;
          });
        }

        // Build the HTML to display the filtered data
        var html = "";
        data.forEach(function(item) {
          html += "<h2>" + item.name + "</h2>";
          html += "<p>" + item.description + "</p>";
        });

        // Update the category container with the HTML
        categoryContainer.innerHTML = html;
      }
    };
    xhr.open("GET", "app.php?category=" + encodeURIComponent(category), true);
    xhr.send();
  });

});

data.json:

[
  {
    "name": "Apple",
    "description": "A sweet fruit that is good for you.",
    "category": "fruits"
  },
  {
    "name": "Broccoli",
    "description": "A nutritious vegetable that is high in fiber.",
    "category": "vegetables"
  },
  {
    "name": "Milk",
    "description": "A dairy product that is a good source of calcium.",
    "category": "dairy"
  },
  {
    "name": "Carrot",
    "description": "A root vegetable that is crunchy and delicious.",
    "category": "vegetables"
  },
  {
    "name": "Banana",
    "description": "A delicious fruit that is high in potassium.",
    "category": "fruits"
  }
]

app.php:

<?php

// Read the contents of the data.json file
$data = file_get_contents('data.json');

// Decode the JSON data into an array of items
$items = json_decode($data, true);
$itm = json_encode($items);

// Check if the category parameter is set and filter the items by category
if (isset($_GET['category'])) {
    if($_GET['category']!=="all"){
    $category = $_GET['category'];
    $items = array_filter($items, function($item) use ($category) {
        return $item['category'] == $category;
    });
    }
}

// Set the content type header to indicate that we are sending JSON data
header('Content-Type: application/json');

// Send the filtered items as JSON data
if($_GET['category']!=="all"){
echo json_encode(array_values($items));
}else{
    echo $itm;
}

This code reads the contents of the data.json file, decodes the JSON data into an array of items, filters the array by category if the category parameter is set, and then sends the filtered items as JSON data to the web page.

If I select a specific category(working):

If I select the "All" category (not working):

I want to see all categories.

Where did I go wrong? Thank you!

Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
uzxzn
  • 1
  • 3
  • Welcome to Stack Overflow! This is a good opportunity for you to start familiarizing yourself with [using a debugger](https://stackoverflow.com/q/25385173/328193). When you step through the code in a debugger, which operation first produces an unexpected result? What were the values used in that operation? What was the result? What result was expected? Why? To learn more about this community and how we can help you, please start with the [tour] and read [ask] and its linked resources. – David Feb 22 '23 at 18:57
  • What's the point of filtering data in js when it's already filtered in php? – u_mulder Feb 22 '23 at 19:00
  • 1
    `if (category) {` is always true in js. Even if selected category is "all". And of course you don't have items with category "all". – u_mulder Feb 22 '23 at 19:02
  • @u_mulder Thanks, I fixed it. What can I do to make all categories visible when I log in? When I refresh the page nothing shows up, only when I change the category it works. How to fix this? – uzxzn Feb 23 '23 at 15:20

0 Answers0