Data from post in ajax request works but PHP still says undefined index

This is pretty weird to me and I can’t seem to find what’s wrong.
I’ll elaborate on what I’m doing now.

  • I have this page called “categoriasCatalogo.php” where I want a navbar to appear, I have this navbar in another file named “navbar.php”.
  • I have an Ajax request sending the level of navbar I want and the catalog’s ID, it’s correctly routed and the navbar displays properly, the payload has the correct data and the correct names, but I get an error saying the navbarlv index is undefined. Which cannot be as both match and as I said, the navbar is displaying and working.
  • This aproach worked in another file without any issues, only difference being the other file is in the root folder like navbar.php.

I’ll provide some stuff that might be useful:

  • This is the Ajax request, executed on the document.ready function in the “categoriasCatalogo.php” file, located in the bottom part of the code, making sure the container that will hold the navbar exists.
const getNavBar = (idcat) => {
        let paquete = "navbarlv=2&idcatalogo="+idcat;
        $.ajax({
            type: "POST",
            url: "../navbar.php",
            data: paquete,
            dataType: "html"
        }).fail(function(respuesta) {
            //TODO: Modal fail
        }).done(function(respuesta) {
            document.getElementById("navbarlvl2").innerHTML = respuesta;
            
        })
    }
  • Var_dump returns this:
Notice: Undefined index: navbarlv in C:laragonwwwMcPDFnavbar.php on line 3
NULL
string(1) "2" 
  • Payload looks like this:
{
    "navbarlv": "2",
    "idcatalogo": "9"
}
  • The beggining of “navbar.php” looks like this, the catalog ID (“idcatalogo”) is requested within the function navbarlvl2() and it’s working:
require_once "config.php";
$navbarLV = $_POST["navbarlv"];
echo var_dump($navbarLV);



switch($navbarLV){
    case "1":
        navbarlvl1();
        break;
    case "2":
        navbarlvl2();
        break;
}

This is my very first post here, thanks a lot in advance and hope you’re having a nice day 🙂

Using JavaScript to clear array values on buttons onclick?

Learning JS and needed some help.
Thanks to stack overflow, I now have a function that displays list of subjects onload. I’d like the button values to clear when clicked and replaced with array of second function. This is creating a new set of buttons, I can see where the problem is but not sure how to correct it. I’ve tried a few ways but no luck, here is the basic code. It is assigned to ‘subjects’ div in HTML doc.

let subjectArray = ['Maths', 'English', 'Science', 'IT'];

function printSubjects() {
    for (let i = 0; i < subjectArray.length; i++) {
        let sub = document.createElement('button');
        let txt = document.createTextNode(subjectArray[i]);
        sub.append(txt);
        subjects.appendChild(sub);
        sub.className = "btn btn-outline-primary mb-2";
    }
}
let testArray = ['Test 1', 'Test 2', 'Test 3', 'Go Back'];
function printTest() {
    for (let i = 0; i < testArray.length; i++) {
        let test = document.createElement('buttons');
        let txt = document.createTextNode(testArray[i]);
        test.append(txt);
        subjects.append(test);
        test.className = "btn btn-outline-secondary mb-2";
    }
}
window.onload = printSubjects();

document.body.addEventListener("click", printTest, {
    once: true
})

Determine if one array contains all elements of another array, including any duplicates

I’m looking for a function that returns true if and only if a given array includes all the elements of another target array which may include two or more occurrences of the same element.

Sample data:

const target = [ 1, 3, 3 ];
const array1 = [ 1, 2, 3, 4 ]; // false
const array2 = [ 1, 3, 3, 4 ]; // true
const array3 = [ 1, 3, 4, 3 ]; // true
const array4 = [ 3, 2, 1, 3 ]; // true

This question’s answer is close but doesn’t account for duplicates in target array.

This question’s answer works for Ruby but I’m looking for a Javascript solution.

When not accounting for duplicates, .indexOf() and .includes() make it rather easy and there are elegant one-liner solutions. But I’m unsure how to keep track of duplicates and suspect a more iterative approach is needed.

import JSON to SCSS/SASS

I have a theme.json and a index.scss file which customises material design styles.

theme.json

{
    "palette": {
      "primary": {
        "main": "#1A1A1A"
      },
      "secondary": {
        "main": "#993355"
      },
      "error": {
        "main": "#B00020"
      },
      "info": {
        "main": "#EAF4FC"
      },
      "text": {
        "primary": "#1A1A1A"
      },
      "other": {
        "accents": ["#BCAAA4", "rgba(128, 236, 40, 0.5)"]
      }
    },

  }

index.scss

@import "../theme/theme.json";

@use "@material/theme" with (
    $primary: $palette.primary.main, ???????
    $secondary: #018786,
    $background: #fff,
    $surface: #fff,
    $error: #b00020,
    $on-primary: #fff,
    $on-secondary: #442b2d,
    $on-error: #fff,
);

@use "material-components-web/material-components-web";

Is there an easy way to import json object values to scss similar to my first variable in my scss file? Thanks in advance

Next.js Router.push with non-public parameters

Is there a way to call router.push() in Next.js and pass state to the next url without using query: {params}? Using query exposes the parameters in the URL. I’m interested in sending the user to a new page for an authentication operation so I need the credentials to be sent securely.

Event listener stops listening

I’ve set up a 16×16 square grid and made the background of each square change color when hovered over.

I then have a button to clear the starting grid and prompt the user for dimensions for a new grid, which then sets up the next grid and seems to work fine.

However, at this stage, the existing Event Listener for the ‘mouseover’ event no longer works.

I’ve checked all the syntax and for any variable name clashes and have come unstuck – please help!

My script/html/css is here: https://codepen.io/Turbo124/pen/KKyMzxX

and my script is also shown below – thank you.

const gridContainer = document.querySelector('#grid-container');

function makeGrid(rows, cols) {
    gridContainer.style.setProperty('--gridRows', rows);
    gridContainer.style.setProperty('--gridCols', cols);
    for (let i = 0; i < (rows * cols); i++) {
        let newCell = document.createElement("div");
        // newCell.textContent = (i + 1);
        newCell.classList.add("cells");
        gridContainer.appendChild(newCell);
    }
   
}

makeGrid(16,16);

document.querySelectorAll('.cells').forEach(cell => {
    cell.addEventListener('mouseover', event => {
        cell.style.backgroundColor = "blue";
        console.log("hover");
    })
})

button = document.getElementById("button");
button.addEventListener("click", clearGrid);
button.addEventListener("click",setGrid);

function clearGrid() {
    let temp = gridContainer.childElementCount;
    for (let i = 0; i < temp; i++) {
    gridContainer.removeChild(gridContainer.childNodes[0]);
    }
}

function setGrid() {
    let temp = prompt("Enter number of squares per side")
    makeGrid(temp, temp);

};

Change timing of gsap animation after condition is met

I’m trying to build my own slot machine using PixiJS for my rendering and animating it with GSAP. I have some reels that spin after clicking a button, also symbol textures are swapped when they are no longer in view. So there is a decent start, but because i’m not sure if the way i build the base will work for future functionalities, i’m playing around to see if i can get some of these to work.

Here is a sandbox of the project so far: https://codesandbox.io/s/black-sea-13g0e?file=/src/js/Reels.js

What i’m trying to do now
I’m trying to see if i can do things with the animation when a condition is met. In slots u will often see that a suspense is building when the user is close to getting a bonus-game. In the example below u need 3 fishes on the reels for the bonus, and as you can see when 2 are hit the animation of the last reel takes longer.

enter image description here

What i tried

  1. In my Reels.js i multiplied certain values like duration and y when the condition is met. This doesn’t seem to do well with the setTimeout and i notice no difference.

  2. Trying to work with a gsap timeline where i then manage the timings instead of using a setTimeout Something like:

animate(reel, i) {
  const self = this;
  let delay = 0.2 * i;
  if (this.factor > 1) {
    delay = 0;
  }
  const tl = gsap.timeline();

  for (let j = 0; j < reel.children.length; j++) {
    let lastY = reel.children[j].y;

    tl.to(reel.children[j], {
      duration: 1.25 * this.factor,
      y: `+=${this.totalY * this.factor}`,
      ease: "back.inOut(0.4)",
      onComplete: () => self.calculateResults(reel.children[j], i, j),
      modifiers: {
        y(y) {
          let newY = parseFloat(y) % 800;

          let difference = newY - lastY;

          if (newY < lastY && difference < -100) {
            reel.children[j].swapSymbol(reel.children[j]);
          }
          lastY = newY;

          return newY;
        }
      }
    }, delay);
  }
}

calculateResults(symbol) {
  if (symbol.texture.textureCacheIds[0] === 'symbolYellow') {
    this.factor = 3;
    console.log('Add some suspense!')
  }
}

What i’m looking for
Is there a way to do this with the way i organized my reels?

How do I change only one variable into “p” tags? [duplicate]

How to change only one variable into multiple p tags? My code does not working.
Link to the entire code on CodePen: https://codepen.io/xxiirr/pen/zYPBqEa

At the beginning, the quantity of the first three products is equal to 10 and the quantity of the fourth product is 5. After pressing the button, the quantity of all products changes to 6. I know why it doesn’t work well but I don’t know how to change it to work properly. The problem is probably in the part of the code responsible for update, i.e. updatedProductsList. Attached below.

JavaScript



const updatedProductsList = () => {
  products.map((item) => {
    document.querySelectorAll("span").forEach((e) => {
      e.innerText = `${item.getCurrentCount()}`;
    });
  });
};

HTML

<body>      
      <div class="product">
          <h2 id='products'>
              `Number of products:  ${products}
          </h2>
      </div>
      <button type="button" onclick="Product.add()">Increase the quantity by one</button>
    </body>

Is there a way to make svgs reactive using javascript

I am making a website that is designed to overflow to the left and right, even on desktops. To make this more ergonomic, I want to put svg arrows on the sides that scroll the page. However, when I move the mouse over them, nothing happens, even when I’ve declared the appropriate event listener (and tested it with other elements)

let arrow = document.getElementById("arrow");
arrow.onmouseenter = scroll;

function scroll() {
  window.scrollBy(-1000, 0);
}
#bigBox {
  min-width: 300vw;
}

#arrowHolder {
  position: sticky;
  width: 10vw;
}

svg {
  height: 7em;
  margin-top: calc(50vh - 3.5em);
}
<body>
  <div id="bigBox">
  </div>
  <div id="arrowHolder">
    <svg viewbox="0 0 200 300">
       <polygon id="arrow" points="0,150 200,0 200,300"/>
    </svg>
  </div>
</body>

Of course, answers should also work in other situations with other events and functions, as this is obviously far from the only potential use of javascript activating svgs

How to rerender {#each array} block in svelte after you push something to an array

Hello I’m making a comment section for my website which works but when I push an object to an array my {#each} block doesn’t update here is this block of code

            {#each commentsScript as { userName, rating, comment }, i}
                <div class="flex">
                    <div class="w-1/4">
                        <h5>{userName}</h5>
                        <h5>{rating}</h5>
                    </div>
                    <div class="w-3/4">
                        <p>{comment}</p>
                    </div>
                </div>
            {/each}

In my script section, I push a new comment to an array and it does show up after I refresh the page but I want to rerender it as soon as the user leaves a comment so the user would see hes/her own comment so is there any way I can rerender it?

Changing color of selected text using document.execCommand() is not giving the range indexes we get from window.getSelection()

I’m trying to change the color of selected text using document.execCommand() using the following code from link. The problem is that i need to get the range index values of selected text as well and this code is not giving the exact index values which we get by window.getselection().getRangeAt()

function makeEditableAndHighlight(colour) {
    var range, sel = window.getSelection();
    if (sel.rangeCount && sel.getRangeAt) {
        range = sel.getRangeAt(0);
    }
    document.designMode = "on";
    if (range) {
        sel.removeAllRanges();
        sel.addRange(range);
    }
    // Use HiliteColor since some browsers apply BackColor to the whole block
    if (!document.execCommand("HiliteColor", false, colour)) {
        document.execCommand("BackColor", false, colour);
    }
    document.designMode = "off";
}

function highlight(colour) {
    var range, sel;
    if (window.getSelection) {
        // IE9 and non-IE
        try {
            if (!document.execCommand("BackColor", false, colour)) {
                makeEditableAndHighlight(colour);
            }
        } catch (ex) {
            makeEditableAndHighlight(colour)
        }
    } else if (document.selection && document.selection.createRange) {
        // IE <= 8 case
        range = document.selection.createRange();
        range.execCommand("BackColor", false, colour);
    }
}