Display JSON Data by Category. Not all categories are visible

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!

How does this link work that uses <a with no href and id instead?

I am trying to understand the way the links on a page are working because I like the design.

This is the live page:

https://www.infohio.org/resources/g68

This is how the links are set up in the source code:

<a  style='color: #202020' class='resourcelink'  id="resourcelinktitle61570">
  <div class='zoo-teaser-title uk-margin-small'> Book Nook </div>
  <div class='zoo-teaser-desc uk-margin-small'> Explore, create, and share video book trailers. Includes recommended web tools for creating book trailers, lesson plans, and other teacher resources. Lexile reading levels included.</div>
</a>

I’ve never seen a link like this. Can someone explain how it’s working?

I tried recreating the code on a page on my local machine and can’t get the links to work.

Why product array is not displaying all elements while using state from useSelector?

Here product is not showing all elements from the array. This is Home Code.
I made a schema of products now I made a reducer.js file in which I assigned products=> array now this fetch details from productAction.js everything works correctly and shows product[0] as a result but after applying map function in home.js product[1]-product[10] does not show up on screen.

import React, { Fragment, useEffect } from "react";
import { CgMouse } from "react-icons/cg";
import "./Home.css";
import ProductCard from "./ProductCard.js";
import MetaData from "../layout/MetaData";
import { clearErrors, getProduct } from "../../actions/productAction";
import { useSelector, useDispatch } from "react-redux";
import Loader from "../layout/Loader/Loader";
import { useAlert } from "react-alert";

const Home = () => {
  const alert = useAlert();
  const dispatch = useDispatch();
  const { loading, error, products } = useSelector((state) => state.products);

  useEffect(() => {
    if (error) {
      alert.error(error);
      dispatch(clearErrors());
    }
    dispatch(getProduct());
  }, [dispatch, error, alert]);

  return (
    <Fragment>
      {loading ? (
        <Loader />
      ) : (
        <Fragment>
          <MetaData title="eDavaa" />

          <div className="banner">
            <p> </p>
            <h1> </h1>

            <a href="#container">
              <button>
                Scroll <CgMouse />
              </button>
            </a>
          </div>

          <h2 className="homeHeading">Featured Products</h2>

          <div className="container" id="container">
            {products &&
              products.map((product) => (
                <ProductCard key={product._id} product={product} />
              ))}
          </div>
        </Fragment>
      )}
    </Fragment>
  );
};

export default Home;

Here is Product Reducer Code

export const productsReducer = (state = { products: [] }, action) => {
    switch (action.type) {
        case ALL_PRODUCT_REQUEST:
        case ADMIN_PRODUCT_REQUEST:
            return {
                loading: true,
                products: [],
            };
        case ALL_PRODUCT_SUCCESS:
            return {
                loading: false,
                products: action.payload.products,
                productsCount: action.payload.productsCount,
                resultPerPage: action.payload.resultPerPage,
                filteredProductsCount: action.payload.filteredProductsCount,
            };

        case ADMIN_PRODUCT_SUCCESS:
            return {
                loading: false,
                products: action.payload,
            };
        case ALL_PRODUCT_FAIL:
        case ADMIN_PRODUCT_FAIL:
            return {
                loading: false,
                error: action.payload,
            };

        case CLEAR_ERRORS:
            return {
                ...state,
                error: null,
            };
        default:
            return state;
    }
};

and Here is backend code ->

exports.getAllProducts = catchAsyncErrors(async (req, res) => {

    const resultPerPage = 8;
    const productsCount = await Product.findById(req.params.id);

    const apiFeature = new ApiFeatures(Product.find(), req.query).search().filter().pagination(resultPerPage);
    const products = await apiFeature.query;
    res.status(200).json({
        success: true,
        products,
        productsCount
    });
})

Here is product action code


// Get All Products
export const getProduct =
  (keyword = "", currentPage = 1, price = [0, 25000], category, ratings = 0) =>
  async (dispatch) => {
    try {
      dispatch({ type: ALL_PRODUCT_REQUEST });

      let link = `/api/v1/products?keyword=${keyword}&page=${currentPage}&price[gte]=${price[0]}&price[lte]=${price[1]}&ratings[gte]=${ratings}`;

      if (category) {
        link = `/api/v1/products?keyword=${keyword}&page=${currentPage}&price[gte]=${price[0]}&price[lte]=${price[1]}&category=${category}&ratings[gte]=${ratings}`;
      }

      const { data } = await axios.get(link);

      dispatch({
        type: ALL_PRODUCT_SUCCESS,
        payload: data,
      });
    } catch (error) {
      dispatch({
        type: ALL_PRODUCT_FAIL,
        payload: error.response.data.message,
      });
    }
  };

Product Showing only one element that is product[0]? What should I Do.

I tried everything. But still no solution.

Three.js create n meshes to form a smooth 90 degree donut

I am trying to find an algorithm to have the following generated in Three.js.
Expected outcome (Pardon my drawing skills)
The amount of meshes to form the 90 degree donut, the thickness and the padding between them should be variable.

I know that you can create something like that with the TorusGeometry setting the radial segments to 2 and reducing the arc along the lines of:

const geometry = new THREE.TorusGeometry( 10, 3, 2, 100 );
const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
const torus = new THREE.Mesh( geometry, material );
scene.add( torus );

But this does not work because as seen in my expected outcome, I need seperate meshes. So I researched further and encountered the ShapeGeometry. I think the way to go is with ShapeGeometry.

const generateArc = (padding, thickness, count) => {
     const arcShape = new THREE.Shape()
        .moveTo( 50, 10 )
        .absarc( 10, 10, 40, 0, Math.PI * 2, false );
}

But I can’t figure out how to do the correct math to generate these seperate mesh arcs around.
Is my approach with ShapeGeometry the right one? and if so how do I generate the right meshes with the Shape geometries.

Troubleshooting “Non-Error promise rejection captured with value: Object Not Found Matching Id” in Sentry, from MERN App

enter image description here

This is an issue we’ve had for a while now, although this error has recently been appearing much more frequently for us in Sentry. Clicking into the issue does not give us much more info:

enter image description here

Like any painful error, we are having difficulty recreating the issue on our end – going to these website URLs does not cause this issue locally for me (although, I am on Mac, not Windows). A few related questions we have:

  • is this something we can safely ignore in Sentry?
  • if safe to ignore, is it better to ignore in the Sentry website in the Browser by clicking the ignore button, or by adding ignoreErrors into our Sentry.init() with

We initialize Sentry in our React App with this snippet in our index.js file:

Sentry.init({
    dsn: config.dsn,
    integrations: [
        new Integrations.BrowserTracing()
    ],
    tracesSampleRate: 1.0
});

and we initialize in our Node App in it’s index.js file:

const sentryDsn = env === 'development' ? null : config.SENTRY_DSN;
Sentry.init({ dsn: sentryDsn, tracesSampleRate: 1.0 });

I show both initializations as I am not sure if this is an error coming from our React app or our Node App, although I think it’s from our React App. Also, from this article, it seems like we could ignore these errors directly from our app with the following added to Sentry.init({}):

ignoreErrors:[
   "Non-Error exception captured",
   "Non-Error promise rejection captured"
]

We also found this related github issue, although it doesn’t seem like there are any great conclusions in here as well. Any recommendations as to what our best course of action is here, and how we could potentially further troubleshoot this, would be super helpful! Thanks!

Google Tag Manager trigger based on changed variable in datalayer

I have a variable watchedVariable that can either be “ABC” or “DEF” and a tag that should fire every time the value of watchedVariable changes from “ABC” to “DEF” or vice versa.

I tried to write a javascript that pushes e.g. "event" : "watchedVariable changed" based on an older entry I found, but I can’t apply it to my use case (my js skills are pretty basic).

I adjusted the name of {{watchedVariable}} and the dataLayer.push command at the end. Is there more to adjust?

Would be super thankful for any help on this!

<script>
var someEventIsTriggered = function(e) {
    var target = $('input#watched');
    var lastEvent = dataLayer
                        .filter(function (e) { return e.event === 'gtm.customEvent'; })
                        .pop();
    var lastValue = lastEvent instanceof Object 
                        ? lastEvent[{{watchedVariable}}] 
                        : false;

    // Trigger a generic "gtm.click" event on every click
    dataLayer.push({
        "event": "gtm.customEvent",
        {{watchedVariable}}: target.val()
    });

    if (lastValue !== target.val()) {
        dataLayer.push({
        "event": "watchedVariable changed"
    });
    }

};
</script>```

Is there a best practise way to get named anchor links rather than using IDs?

Bit of a novice, but I’ve got some legacy code to generate a Table of Contents based on adding an incremented ID to each of the H2 elements on a page.

As these can change order, I’d be hesitant to link to blah.com/help/article-1#4.

In the scenario that the anchor link’s H2 text is “Creating a post”, what can I do to this code to get the ID to be creating-a-post, resulting in the dynamic link being blah.com/help/article-1#creating-a-post?

const $headers = $(".article-body > h2, h3");

$headers.each((i, el) => {
  const $el = $(el);

  // skip it if it already has a link inside
  if ($el.has("a").length != 0) {
    return;
  }

  let idToLink = "";

  // skip it if it already has an id
  if ($el.attr("id") === undefined) {
    // give it ID to match
    idToLink = "" + i;
    $el.attr("id", idToLink);
  } else {
    // make sure the ID matches
    idToLink = $el.attr("id");
  }
});

$(document).ready(function () {
            setTimeout(() => {
                // Get ToC div
                if(document.querySelectorAll('.article-body > h2').length > 0) {
                
                toc = document.getElementById("ToC"); 
              //Add a header
                tocHeader = document.createElement("h2");
                tocHeader.innerText = "In this article";
                toc.appendChild(tocHeader); 
              // Get the h2 tags — ToC entries

                tocList = document.createElement("ul");
                // tocContainer.appendChild(tocList);
                // document.getElementById("div").appendChild(tocList);

                $('.article-body > h2').each(function () {
                    tocListItem = document.createElement("li");
                    // a link for the h2
                    tocEntry = document.createElement("a");
                    tocEntry.setAttribute("href", "#" + $(this).attr('id'));
                    tocEntry.innerText = $(this).text();
                    tocListItem.appendChild(tocEntry);
                    tocList.appendChild(tocListItem);
                });
                toc.appendChild(tocList);

                }
            });
        });

Is this even the best route?

Add a before/after slider to lightGallery

Using lightGallery and would like to implement one inline gallery with a before/after slider on each image.
Both are working fine using them independently: BeerSlider and lightGallery.

Is there somebody wo got this working?
I tried several ways already without success.
One of my attempt was to add the BeerSlider classes as a caption and append them to the lg-item element:

  // photo before after
  const beforeAfterContainer = document.getElementById("before-after");
  const beforeAfterInlineGallery = lightGallery(beforeAfterContainer, {
    container: beforeAfterContainer,
    dynamic: true,
    appendSubHtmlTo: ".lg-inner",
    dynamicEl: [
      {
        src: "https://loremflickr.com/640/480?random=1",
        thumb: "https://loremflickr.com/320/240?random=1",
        subHtml: `<div id="beer-slider" class="beer-slider" data-beer-label="before" data-beer-start="50">
            <img src="https://loremflickr.com/640/480?random=1" />
            <div class="beer-reveal" data-beer-label="after">
                <img src="https://loremflickr.com/640/480?random=2" />
            </div>
                </div>`,
      }
     //....
    ],
  });
  beforeAfterInlineGallery.openGallery();

  $("#beer-slider").each(function (index, el) {
    $(el).BeerSlider({ start: $(el).data("beer-start") });
  });

Thats not working at all. Additionally I tried to use the lightGallery selector to get the Beer Slider reveal image ignored by lightGallery. But this is not working at all, as one instance destroys the others (as far as I understand those scripts correctly).

Any ideas how to get both working together?
I really don’t need to use BeerSlider – if somebody got any other before/after plugin working with lightGallery I can switch to it.

Thanks Guys!

How to list products from b2b api?

im a simple user (reseller) and i got a b2b api key with some sample code. I want to list all the products from a company. I have a website (simple bootstrap3 (html,css)), not webshop. I just want to list on a page.

The Sample Code:

https://api.wycena.keno-energy.com,
POST: {
    "apikey": "A5TTRfG453d24F",
    "method": "GetProductsList",
    "parameters": [
            {
                "ShowGroups": "1",
                "ShowIndex": "1"
            }
    ]
}

I want to write out: GetProductInfo ; GetProductList ; GetProductsWarranty.

How can i get these? thank you for helping. I have wampserver, js.node and sublime text.

API DOCU: https://api.wycena.keno-energy.com/Dokumentacj_en.html

Determining incomplete sections in Javascript object

I have a Javascript object with a few sections; namely, banking,fitment,personal_info,vehicle.

The object is structured as follows:

{
  banking: {
    account_number: null,
    account_type: null,
    bank_name: null,
    debit_day: null
  },
  fitment: {
    date: null,
    terms: null
  },
  personal_info: {
    email: null,
    IDNumber: null,
    mobile: null,
    name: null,
    residential_address: null,
    surname: null,
    title: null,
    work_address: null,
    work_tel: null
  },
  vehicle: {
    brand: null,
    colour: null,
    model: null,
    registration: null,
    vin: null,
    year: null
  }
}

By default, all values within the object and its “nested sections” have a value of null.

I’m trying to figure out a way to categorize the sections into 3 different categories, namely:
empty, partial and complete.

empty” being a case that all values within a section are set as null.

partial” being that some values within a section have been set (not all null)

complete” being that no values within a section are set to null. All have values.

My first attempt was with utilizing the Underscore library with _.some(), however I can’t seem to wrap my head around catering for all 3 category scenarios.

Some help and guidance will be much appreciated.

Thanks!

HTML Table when a row is double clicked, a new form page will open autofilled

I am very new to webapp with appscript. I have the below code. It will filter out the google sheet data with the session.user’s name only and show as a table in html page. once the user double clicks a cell it will open a new form. I want to autofill this form page with the row they have double clicked on.

My code works fine with generating the table, double clicking and opening data. but it does not get the values autofiilled

function doGet(e) {
  Logger.log( Utilities.jsonStringify(e) );
  if (!e.parameter.page) {
    // When no specific page requested, return "home page"
    return HtmlService.createTemplateFromFile('homePage').evaluate();
  }
  // else, use page parameter to pick an html file from the script
  return HtmlService.createTemplateFromFile(e.parameter['page']).evaluate();
}


function getScriptUrl() {
 var url = ScriptApp.getService().getUrl();
 return url;
}


function getData() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data');
  var data = sheet.getDataRange().getValues();
  var headerRow = data.shift(); // remove the header row from the data array
  var filteredData = [headerRow]; // add the header row to the filtered data array
  for (var i = 0; i < data.length; i++) {
    var row = data[i];
    if (row[6].indexOf(Session.getActiveUser().getEmail()) != -1) {
      filteredData.push(row);
    }
  }
  return filteredData;
}


function fillForm(values){

  var list = getData();
  var newItem = list.filter(v=> v[0] == values); 
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data');
  sheet.getRange("k1").setValue(values);
  var uid = sheet.getRange("k1").getValue();
  console.log("gf"+ values);
   return values;
 
}

Html code for displaying table

<!DOCTYPE html>
<html>
  <head>
  
     <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" 
        content="IE=edge">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
    <base target="_top">
<script>
    function addthisre(values)
    {
     
      google.script.run.addrec(values);
    }
    </script>


  </head>
  <!-- Add a link to the local Style Sheet for further control over the layout-->
    <?!= HtmlService.createHtmlOutputFromFile('DisplayContentCSS').getContent(); ?>
  
  <body>



    <h1>Contents</h1>
    <table border="1" cellpadding="5px" id="myTable" >
    <?var tableData = getData();?>
    <?for(var i = 0; i < tableData.length; i++) { ?>
      <?if(i == 0) { ?>
        <tr >
        <?for(var j = 0; j < tableData[i].length; j++) { ?>
        <th><?= tableData[i][j] ?></th>
        <? } ?>
        </tr>
      <? } else { ?>
        <tr >
        <?for(var j = 0; j < tableData[i].length; j++) { ?>
        <td><?= tableData[i][j] ?></td>
        <? } ?>
        </tr>
      <? } ?>
    <? } ?>
    </table>


   


<div class="container">
        <button id="btn" >
            <p id="btnText" onclick="sendsheetmail()">Send Mail</p>
            <div class="check-box">
                <svg viewBox="0 0 50 50">
                    <path fill="transparent" d="M14.1 27.2l7.1 7.2 16.7-16.8" />
                </svg>
            </div>
        </button>
    </div>
    <script type="text/javascript">
        const btn = document.querySelector("#btn");
        const btnText = document.querySelector("#btnText");

        btn.onclick = () => {
            btnText.innerHTML = "Success!!";
            btn.classList.add("active");
        };
    </script>
</body>





  </body>
  <?var url = getScriptUrl();?>
  <script>
  var table = document.getElementById('myTable');
  var rows = table.getElementsByTagName('tr');
  for (var i = 0; i < rows.length; i++) {
    rows[i].addEventListener('dblclick', function(event) {
      var cells = event.currentTarget.getElementsByTagName('td');
       console.log(cells);
      var values = [];
      for (var j = 0; j < 12; j++) {
        values.push(cells[j].textContent);
        
          
window.open('<?=url?>?page=editForm','_top');
      }
      google.script.run.fillForm(values);
      
      console.log(values); // Output the row values to the console


    });
  }
</script>
</html>




html content for new form..

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script>
    function addEditedRow()
    {
      var firstname = document.getElementById("firstname").value;
      var lastname = document.getElementById("lastname").value;
      var email = document.getElementById("email").value;
      var place = document.getElementById("place").value;
      google.script.run.AddRecord(firstname, lastname ,place, email);
      document.getElementById("firstname").value = '';
      document.getElementById("lastname").value = '';
      document.getElementById("email").value = '';
   document.getElementById("place").value = '';
    }
   
</script>


  </head>
  <!-- Add a link to the local Style Sheet for further control over the layout-->
    <?!= HtmlService.createHtmlOutputFromFile('editFormCSS').getContent(); ?>
  <body>

   

     <? var rowvalues = fillForm(); ?>





      <div class="form">
      <div class="title">Welcome</div>
      <div class="subtitle">Subtitle Goes Here</div>


      
      <div class="input-container ic1">
        <input id="team" class="input" type="text" placeholder=" "  value="<? rowvalues ?>"  readonly  />
        <div class="cut"></div>

        <label for="team" class="placeholder">Team</label>
      </div>
      <div class="input-container ic2">
        <input id="lastname" class="input" type="text" placeholder=" " />
        <div class="cut"></div>
        <label for="lastname" class="placeholder">Last name</label>
      </div>
       
      <div class="input-container ic2">
        <input id="email" class="input" type="text" placeholder=" " />
        <div class="cut cut-short"></div>
        <label for="email" class="placeholder">Email</label>
      </div>
      <input type="button" class="submit" value="Add" onclick="addEditedRow()" />
    </div>





  </body>



</html>

How to retrieve a Slack UserID from known Username in Javascript

I am trying to create a button in Javascript that will link me to a dm in Slack with a specific user. I am just learning about API and GET methods and cannot figure out how to find the Slack UserID from a known Username.

Here is the button I am trying to create. But I am unable to find the UserID using the UserName.

//Have UserName
var = userName

// Get UserID using UserName
let btn = document.createElement("button")
    btn.innerHTML = "Slack Button"

//Button redirecting to Slack DM with specific user
btn.onclick = function(){
        window.open((slackUrlLink).append(UserID));
}

Can I make an MUI List item trigger a HTML Script for Jira Issue Collector?

I have a sidebar made with MUI. One of the sidebar options is feedback. I want to use the Jira Issue Collector on this feedback option, but I have not been able to get the script to work with the ListItem.

The Script and ListItem:


<script type="text/javascript" src="link" ></script>

<ListItem
    button
    // component="a"
    // href="#"
    // target="_blank"
>
    <Typography className={classes.closedTxt} hidden={open}>
        Feedback
    </Typography>
</ListItem>