X-Forwarded-For in the request-ip package potential bug

I was reading the request-ip code. (Link here) and I noticed that when dealing with the X-Forwarded-For part it is treated as if it will only be a string always. when in reality it’s very possible that it can be an array of IPs, and when it wants to get client IP from X-Forwarded-For, it assumes that it is just a string of IPs concatenated with a ‘,’ character

I expected it to join the IPs with a ‘,’ character if it was an array, but that’s not the case. what am I doing wrong?

Making a website on Squarespace, added a desktop hamburger menu and having issues

I have been working on Squarespace 7.1 to create a website for my client and they wanted a navigation with links and a hamburger. I have done this successfully using this article:
Desktop Hamburger

I was able to successfully change the colors of the links inside the overlay but I am having issues changing colors of the closing ‘x’ in the top right corner.

the issue

This is the custom css code I have included into squarespace:

// BETTER BURGER
/* This will handle styling the burger icon color*/
a[href='/burger'] path {
  fill: white !important;
}

/*This deals with the burger size*/
a[href='/burger'] svg {
  height: 50px !important;
  width: 50px !important;
}

/* Removes the underline set by Squarespace active class */
a[href='/burger'] {
  background: none !important;
}

/* This removes the black hover box under the burger menu */
.header-nav-folder-content {
  display: none;
}

/* This will handle styling the background color of the burger overlay */
better-burger {
  background: #005798;
}

/* This will handle styling the links inside the burger menu */
better-burger a {
  color: white;
  font-size: 45px !important;
}
/* styling links inside burger menu when hovering */
better-burger a:hover{
  color: #F89623;
}

better-burger.burgerToggle svg path{
  --close-burger: white !important;
}

and this is the link for the javascript file:
https://cdn.jsdelivr.net/gh/ryandejaegher/better-burger@latest/script.js

I have tried doing

better-burger svg{
 color: white;
}

wanting to turn the ‘x’ white, but it just doesn’t wanna do it. Any help would be much appreciated, I can see the class names/issues, I just am struggling to know how to code it into the custom css that I have already existing. Thank you

pass a variable from a loop to a modal

here is my problem

Before deleting a record (id), I would like to have a confirmation message.

I use a modal (bootstrap 4) to inform the user.

So I’m trying to pass an id to my modal. Confirmation is done by clicking on the ‘#btnDelete’ button which triggers an ajax. So I only need one id.

  1. Twig: I performed a loop on datas to retrieve, among other things, Ids and dates
{% for id, d in datas %}
    <tr>                                 
        <td> {{ d|date("d/m/Y - H:i:s")  }} </td>
        <td> <a  data-toggle="modal" href="#" data-target="#modalConfirmDelete" data-id="{{ id }}" class="open-modal"><img src="foo"/></a></td>
    </tr>
</tr>
{% endfor %}

  1. modal
<div class="modal fade" id="modalConfirmDelete" ...>
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                ...
            </div>
            <div class="modal-body">
                ...
            </div>
            <div class="modal-footer">
                <button type="button" data-dismiss="modal">Cancel</button>
                <button type="button" id="btnDelete">Delete</button>
            </div>
        </div>
    </div>
</div>

  1. jquery
$(document).on('click', '.open-modal', function () {
    let id = $(this).data('id');
    $('#btnDelete').on('click', function () {
        console.log(id);
        //ajax
    })
});

  1. When I click on multiple ‘.open-modal’ buttons, the modal seems to save the values ​​(ids) clicked.

Therefore, when I click on ‘#btnDelete’ from the modal, the console.log shows me all the clicked ids

I tried to empty the modal when it closed but without success

$('#modalConfirmDelete').on('hidden.bs.modal', function (e) {
    $(this).empty();
})

I don’t know if my approach is on the right track. Thank you for your feedback

If you have a jquery or js approach, I’m interested

What is my problem with updating data without auto-updating the page?

The problem with updating data without auto-updating the page
please help with this, I provide the code below
if possible, tell me what I’m doing wrong and how to avoid it in the future

frontend

    async getFavoriteUser(userId: string){
        try {
            const response = await MarketService.getFavoriteProducts(userId);
            const favorites = response.data
            return favorites;
        } catch (error) {
            
        }
    }

    async deleteFavorite(favoriteId: number, userId: string){
        try {
            await MarketService.deleteFavorite(favoriteId, userId)
            const favorites = await this.getFavoriteUser(userId);
            console.log(favorites);
        } catch (error) {
            console.error(error);
        }
    }

backend
product controller

    async  getFavoriteProducts(userId) {
        try {
            const currentUser = await UserModel.findById(userId);
            const favoriteProductIds = currentUser.favorites || [];
            const favoriteProducts = await ProductModel.find({ _id: { $in: favoriteProductIds } });
            return favoriteProducts;
        } catch (error) {
            throw error;
        }
    }
    async deleteFavorite(favoriteId, userId) {
        try{
            const currentUser = await UserModel.findById(userId);
            const favorites = currentUser.favorites || [];

            favorites.splice(favoriteId, 1);
            currentUser.favorites = favorites;
            
            await currentUser.save();
            return favorites
        } catch (error) {
        }
    }   

I tried to change it useEffect

useEffect(() => {
    store.getFavoriteUser(store.user.id)
        .then((favoritesData) => {
            setFavoriteProducts(favoritesData.favoriteProducts);
        })
        .catch((error) => {
            console.error("Ошибка при получении избранных товаров:", error);
        });
}, [store]);

here’s how it is output

  <TabPanel value={value} index={2}>
    Избранные товары
    <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 2 }}>
    {favoriteProducts.map((product) => (
        <Card key={product._id} sx={{ width: 305, height: 450 }}>
      {product.name}
        <Button size="small" variant="contained" color='error' onClick={() => handleDeleteFavorites(favoriteProducts.indexOf(product))}>
          Удалить
        </Button>
    </Card>
            ))}
        </Box>
  </TabPanel>

how can i embed trading view widget ticker tape on my ejs file

I am trying to embed the trading view widget tiker tape in my ejs file but is not working on the ejs file but when i use it on my normal html file it works, please what am i doing wrong
this is how am embedding it. am a newbiew

                <!-- TradingView Widget BEGIN -->
<div class="tradingview-widget-container">
  <div class="tradingview-widget-container__widget"></div>
  <script type="text/javascript" src="https://s3.tradingview.com/external-embedding/embed-widget-ticker-tape.js" async>
  {
    "symbols": [
        {
        "description": "",
        "proName": "COINBASE:BTCUSD"
        },
        {
        "description": "",
        "proName": "COINBASE:ETHUSD"
        },
        {
        "description": "",
        "proName": "COINBASE:USDTUSD"
        },
        {
        "description": "",
        "proName": "BITFINEX:XRPUSD"
        },
        {
        "description": "",
        "proName": "COINBASE:SHIBUSD"
        },
        {
        "description": "",
        "proName": "NASDAQ:AAPL"
        },
        {
        "description": "",
        "proName": "NASDAQ:TSLA"
        },
        {
        "description": "",
        "proName": "NASDAQ:AMZN"
        },
        {
        "description": "",
        "proName": "FX:EURUSD"
        },
        {
        "description": "",
        "proName": "FX:GBPUSD"
        },
        {
        "description": "",
        "proName": "OANDA:EURUSD"
        }
    ],
    "showSymbolLogo": true,
    "colorTheme": "dark",
    "isTransparent": true,
    "displayMode": "adaptive",
    "locale": "en"
  }
  </script>
</div>
<!-- TradingView Widget END -->

can someone please guide me on how i can do it using ejs. it shows on my html but not showing on my ejs file

Filter an array via javascript

Good day.

I made a form with inputs with HTML and CSS. Via javascript i put the input data in an array, but now i want to filter in that array.That filter should show me all the input data of the people that ask for one of these destinies. Canarias, Mallorca,Galicia.

let arrViaje = [];

function recoger() {
  let nombre = document.getElementById("name").value
  let origen = document.getElementById("origin").value
  let destino = document.getElementById("destiny").value
  let personas = document.getElementById("people").value
  let fechas = document.getElementById("dates").value

  let viaje = {
    name: nombre,
    origin: origen,
    destiny: destino,
    people: personas,
    dates: fechas
  }
  console.log(viaje)

  arrViaje.push(viaje);
  console.log(arrViaje)

  function filtrar() {
    let ciudadSinFiltrar = "Canarias"
    let ciudad = ciudadSinFiltrar.toLowerCase
    let filteredArray = arrViaje.filter((city) => city.filter(ciudad))
    console.log(filteredArray)
  }
<div class="formulario">
  <form action="">
    <input type="text" class="datos" id="name" placeholder="Nombre">
    <input type="text" class="datos" id="origin" placeholder="Origen">
    <input type="text" class="datos" id="destiny" placeholder="Destino">
    <input type="text" class="datos" id="people" placeholder="Personas">
    <input type="text" class="datos" id="dates" placeholder="Fecha">
  </form>
  <button onclick="recoger()">Mas información</button>
  <button onclick="filtrar()">Filtrar</button>
</div>

Bootstrap navbar overflowing

Here’s the navbar code:

<header>
  <nav class="sticky-top navbar navbar-expand-md bg-body-light border-bottom ">
    <div class="container-fluid">
      <a class="navbar-brand" href="/listings"
        ><b><i class="fa-brands fa-airbnb"></i> WanderLust</b></a
      >
      <button
        class="navbar-toggler"
        type="button"
        data-bs-toggle="collapse"
        data-bs-target="#navbarNavAltMarkup"
      >
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
        <div class="navbar-nav">
          <a class="nav-link" href="/listings">Explore</a>
          <a class="nav-link" href="/listings/new">Airbnb Your Home</a>
        </div>
        <div class="navbar-nav ms-auto">
          <form class="d-flex" role="search">
            <input
              class="form-control me-2"
              id="search-in"
              placeholder="Search destinations"
              aria-label="Search"
            />
            <button class="btn" id="search-btn" type="submit">
              <i class="fa-solid fa-magnifying-glass"></i>Search
            </button>
          </form>
        </div>
        <div class="navbar-nav ms-auto">
          <% if (!currUser){ %>
          <a class="nav-link" href="/signup"><b>Sign Up</b></a>
          <a class="nav-link" href="/login"><b>Log In</b></a>
          <% } %> <% if (currUser){ %>
          <a class="nav-link" href="/logout"><b>Log Out</b></a>
          <% } %>
        </div>
      </div>
    </div>
  </nav>
</header>

Here’s the boilerplate code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>WanderLust</title>
    <link rel="stylesheet" href="/css/style.css" />
    <link
      href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
      crossorigin="anonymous"
    />
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"
      integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA=="
      crossorigin="anonymous"
      referrerpolicy="no-referrer"
    />
    <link
      href="https://api.mapbox.com/mapbox-gl-js/v3.2.0/mapbox-gl.css"
      rel="stylesheet"
    />
    <script src="https://api.mapbox.com/mapbox-gl-js/v3.2.0/mapbox-gl.js"></script>

    <link rel="stylesheet" href="/css/rating.css" />
  </head>

  <body>
    <%- include('../includes/navbar.ejs') %> <%-include('../includes/flash.ejs')
    %>

    <div class="container"><%- body %></div>

    <%- include('../includes/footer.ejs') %>

    <script
      src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
      crossorigin="anonymous"
    ></script>
    <script src="/js/script.js"></script>
  </body>
</html>

When I’m adding the css to boilerplate code the navbar starts to overflow.

Here’s the css code:

* {
  margin: 0;
}

body {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.container {
  flex: 1;
}

/* Navbar */
.navbar {
  height: 5rem;
  background-color: white;
 
}

.fa-airbnb {
  color: #ff5a5f;
}

.nav-link {
  color: black !important;
}

/* Seach Bar */
#search-btn {
  background-color: #ff5a5f;
  color: white;
  border-radius: 25px;
  padding: 0 1rem 0 1rem;
}
#search-btn i {
  display: inline;
  margin-right: 0.5rem;
}

#search-in {
  border-radius: 25px;
  padding: 0.5rem 3rem 0.5rem 3rem;
}

When I remove the navbar height the overflowing is fixed but I want it to be 5rems.
The navbar is content comes out of the 5rem nav bar and merges with the main body content and what ever I do it doesn’t help.

I have been trying to fix it for 3 days but nothing’s working, this is my first full-stack project and I need serious help here.

I tried removing the height and overflow control but nothing worked.

Google Sheet Not receiving Data from front end

Fairly new to this process! Trying to set up a form to submit and then have the data go to a google sheet. I used this guide as a template: https://github.com/levinunnink/html-form-to-google-sheet?tab=readme-ov-file, but for some reason the data isnt being received. No errors on the console log either. Is there a better way to go about doing this?

$(document).ready((function () {
   window.addEventListener("load", function() {
  const form = document.getElementById('#userForm');

  $( "#submitBtn" ).on( "submit", function() {

    e.preventDefault();
    const data = new FormData(form);
    const action = e.target.action;
    fetch(action, {
      method: 'POST',
      body: data,
      url:"MY GOOGLE URL",
    })
    .then(() => {
      alert("Success!");
    })

  } );

});
<form class="section__form" id="userForm">
  <label>YOUR NAME:
                            <input type="text" class="section__form-input" id="Name" name="Name" placeholder="Your Name" required></label>
  <label>EMAIL ADDRESS:
                            <input type="email" class="section__form-input" id="Email" name="Email" placeholder="Email Address" required>
                            </label>
  <button type="submit" class="section__cta" id="submitBtn">LEARN MORE</button></form>

Vuejs initialization Typerror

I am trying to create a new vue application but I keep getting this Type Error, I’ll show you my entire command line. All I did was run npm init vue@latest

npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.

Vue.js - The Progressive JavaScript Framework

TypeError: (0 , import_node_util.parseArgs) is not a function
    at init (C:UsersHPAppDataLocalnpm-cache_npx2f7e7bff16d1c534node_modulescreate-vueoutfile.cjs:4481:72)
    at Object.<anonymous> (C:UsersHPAppDataLocalnpm-cache_npx2f7e7bff16d1c534node_modulescreate-vueoutfile.cjs:4862:1)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

I could not find a solution anywhere

POST method not sending data from JavaScript to PHP file

I have some data stored in local storage that I want to send to a database. This is the JS code:

function sendData(){
          let input = 'new input';
          localStorage.setItem('spins', input);
          // Get user_id from session or wherever it's stored
          var user_id = <?php echo isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 'null'; ?>;

          if (user_id) {
            var value1 = localStorage.getItem('data');
            var value2 = localStorage.getItem('spins');

            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'update_values_to_database.php', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.onreadystatechange = function() {
              if (xhr.readyState === 4 && xhr.status === 200) {
                try {
                  var data = JSON.parse(xhr.responseText);
                  if (data.success) {
                      localStorage.setItem('data', data.data);
                      localStorage.setItem('spins', data.spins);
                      
                  } else {
                      console.error('Failed to retrieve values from the database.');
                  }
                } catch (error) {
                  // Code to handle the error
                  console.error('An error occurred:', error.message);
                  window.location.href = "update_values_to_database.php";
                }     
              }
              };
          }
            xhr.send(JSON.stringify({ user_id: user_id, value1: value1, value2: value2 }));
          }

`

And this it the PHP

<?php
include("database.php");

// Retrieve data from the POST request
var_dump($_REQUEST);
$user_id = $_POST['user_id'];
$value1 = $_POST['value1'];
$value2 = $_POST['value2'];

// Update values in the database for the given user_id
// Modify this query according to your database schema
$query = "UPDATE users SET data = ?, spins = ? WHERE user_id = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 'ssi', $value1, $value2, $user_id);
if (mysqli_stmt_execute($stmt)) {
    echo json_encode(array('success' => true));
} else {
    echo json_encode(array('success' => false));
}
?>

Both the file containing the JS code and that containing the PHP code are in the same directory. I don’t know what I’m doing wrong. Could someone tell me what the error could be?
Thanks in advance.

I’ve tried logging the error and it’s saying that the ‘user_id’, ‘value1’ and ‘value2’ keys are undefined and when I var_dump the $_REQUEST it returns an empty array. When I’ve made sure that all the variables being sent to the PHP file are being defined correctly.

Else statement having issues in JS Console Bell Curve Simulation [duplicate]

My code:

function start() {
    let valueA = readInt("Rand Seed ID: ");
    var points = [0, 0, 0, 0, 0]
    for (var i = 0; i < valueA; i++) {
        var x = randomizer.nextInt(1, 10)
        if (x = 1) {
            points.elem[0]++
        } else {
            if (x = 2 || 3);
            points.elem[1]++
        } else {
            if (x = 4 || 5 || 6 || 7);
            points.elem[2]++
        } else {
            if (x = 8 || 9);
            points.elem[3]++
        } else {
            if (x = 10);
            points.elem[4]++
        }
    }
    println("12.5% Point Lies" + points.elem[0] + "Points");
    println("25% Point Lies" + points.elem[1] + "Points");
    println("50% Point Lies" + points.elem[2] + "Points");
    println("75% Point Lies" + points.elem[3] + "Points");
    println("87.5% Point Lies" + points.elem[4] + "Points");
}

This code is meant to simulate a 5 point bell curve using a randomizer, but the else statement in line 11 refuses to work properly, no matter how much I mess with it. Please help!

I don’t really know what to try from here!

How to correctly search an array of objects and return HTML

I’m building a site search which searches two fields that I have merged into one array of objects, I only need to match the “title” value based upon user’s input, example of my array (collections.js):

export const items = [
{url: '/my-first-post/', title: 'My first post', type: 'Guide', id: 'opt-1'},
{url: '/my-first-tag/', title: 'My first tag', type: 'Tag', id: 'opt-2'},
]

Then in my main JS file I listen for an ‘input’ event:

import { items } from '/js/collections.js';
const search = document.querySelector('#sFilter');
const searchList = document.querySelector('.search__list');
let arrFiltered = [];
let listNodes;

search.addEventListener('input', (evt) => {
  if (search.value) {
    search.setAttribute('aria-expanded', 'true');
    search.parentElement.setAttribute('data-expanded', 'true');
    filterItems(search.value);
  } else {
    search.setAttribute('aria-expanded', 'false');
    search.parentElement.setAttribute('data-expanded', 'false');
    searchList.innerHTML = '';
  }
})

Then my function is:

const filterItems = (term) => {
  arrFiltered = items.filter(item => 
item.title.toLowerCase().trim().includes(term.toLowerCase().trim()));

  arrFiltered.forEach((item, idx) => {
    let res = `<li class="search__item" data-pos="${idx + 1}">
      <a class="search__option" id="${item.id}" href="${item.url}" tabindex="-1">
      <span class="underline">${item.title}</span><span class="search__type">${item.type}</span></a></li>`
    searchList.insertAdjacentHTML('beforeend', res);
  });
  listNodes = document.querySelectorAll('.search__item');

  // Remove DOM nodes not present in arrFiltered
}

What I am trying to do (unsure if going about it the best way), is:

  • Keep the data in the object for looking up (Done)
  • Compare the search.value.toLowerCase().trim() against the item.title.toLowerCase().trim() (Done)
  • Add to the arrFiltered array (Done)
  • Limit that array to a max of 10 results (TODO)
  • Compare input value against item.title, ignoring punctuation: (/["'..,!?]/g, '') & ('-', ' ') (In Progress)
  • Create a collection of <li> items (Done) and append these items to the searchList element (Done)
  • Remove or add those <li> els on subsequent inputs, as opposed to say setting innerHTML = '' on every new input event (TODO)

Obviously in my provided code there is no attempt to remove() elements from the DOM that don’t appear in arrFiltered and I know I can set the innerHTML as an empty string on each input event, but that’s not suitable for this, as “focus” must be maintained on the currently focused element (primarily screen reader users), if that element is still in the arrFiltered array, of course.

An example of my HTML:

<ul class="search__list" id="lBox">
  <li class="search__item" data-pos="1">
    <a class="search__option" id="opt-63" href="/posts/my-first-post/" tabindex="-1">
      <span class="underline">My first post</span><span class="search__type">Post</span> 
    </a>
  </li>
  <li class="search__item" data-pos="2">
    <a class="search__option" id="opt-64" href="/tags/my-first-tag/" tabindex="-1">
      <span class="underline">My first tag</span><span class="search__type">Tag</span> 
    </a>
  </li>
</ul>

So, my question is (finally), I need to remove() DOM elements that are no longer in the arrFiltered array, so I know I need to use a method that will compare an ID present in the nodeList (the <li>.firstElementChild.id) against item.id in the arrFiltered array, what would be a good way of doing this? I have tried map(), filter(), [...spread] and Array.from(), with little success, I’m not saying one or more of those doesn’t work, just I’m obviously doing it wrong :/ so i’d be grateful for a little steer. thank you 🙂

Make a recurring long event every year in FullCalendar v5

I’m struggling to create a recurring long event every year using fullcalendar v5. Let’s say for example I want to create an event starting on December 15th and running until December 31st, and have it repeated every year. How do I achieve this? I’ve found solutions for recurring event every week and month on the “simple recurrence” section of the documentation, but no examples for a yearly basis recurrence. If you could provide a simple example that would be great. Thanks a lot in advance and regards.

request-ip package code explanation please

I was reading request-ip code. (Link here) and I noticed that when dealing with X-Forwarded-For part it is treated as if it will only be a string always. when in reality it’s very possible that it can be an array of IPs, and when it wants to get client ip from X-Forwarded-For, it assumes that it is just a string of IPs concatenated with a ‘,’ character

I expected it to join the IPs with a ‘,’ character if it was an array, but it’s not the case. what am I doing wrong?

i am trying to change my file from page.jsx to index.jsx so that i can create a github pages link

i am trying to change my page.jsx file to an index.jsx file. i am creating my project using reactJS and NextJS but for some reason my homepage doesnt load correctly when i rename the file

This is what is supposed to come up. this was the original homepage when the file name was page.jsx (https://i.stack.imgur.com/FoXsJ.png)

This is what comes up instead once i rename the file to index.jsx(https://i.stack.imgur.com/k4ixz.png)

how do i go about solving this problem please?

here is my github repo link https://github.com/hajimon54/idris-helpdesk

thank you 🙂

i have tried rebuilding the project but that doesnt help and i have also stopped the dev server and ran it again but idk what else to do, im stuck