Why is axios not sending the correct post data?

Why is PHP saying “undefined index request”? The json format looks completely correct to me.

let json = JSON.stringify(
  { request:  "getUser" },
  { username: "test" }
);

const response = await axios.post('http://localhost/projects/serverFiles/index.php', json);

My PHP

<?php
    ini_set("log_errors", 1);

    header('Access-Control-Allow-Origin: *');
    header('Content-Type: application/json');
    
    echo print_r($_POST["request"]);
?>
    

Can’t use firebase in React component, because it’s not initialized [duplicate]

I’m trying to initialize firebase in my App.js, so that I can utilize the user’s auth state throughout multiple scenes. My Sign In/Sign Out logic is tied to 2 seperate button components that are conditionally rendered in my header.

I’m receiving this error, which leads me to believe that the buttons are using “firebase” before it’s init’d.

Uncaught FirebaseError: Firebase: No Firebase App ‘[DEFAULT]’ has been created – call Firebase App.initializeApp() (app-compat/no-app).

App.JS

import React from 'react';
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import Header from './components/core/Header';

firebase.initializeApp({...});

const App = () => (
  <div className="App">
    <Header />
  </div>
)

Is there a way I can initialize firebase to my whole application before the import of Header? Or can I not separate the signIn/Out logic from my App.js?

Why does questions.results rlogs as undefined? [duplicate]

I’m trying to render some data that I’m fetching from the Open Trivia DB. But when I try to map an array (which is the value of am object property), I get undefined on the console.

For now, I want to console.log the array within the object property when the state changes. Later I want to map the results Array to properly render some of the data within the array of objects.

Here’s my code:

export default function App(){
  const [quizScreen, setQuizScreen] = useState(false)

  const questions = (
    fetch('https://opentdb.com/api.php?amount=5&category=26&difficulty=medium')
    .then(res => res.json())
    .then(data =>   data)
  )

const startQuiz = () => {
 
  setQuizScreen(prevScreen => !prevScreen)
  console.log(questions.results) //works if I log questions, but not questions.results


}

This is the data:

{
    "response_code":0,
    "results":[
       {
          "category":"Celebrities",
          "type":"multiple",
          "difficulty":"medium",
          "question":"Which actress&#039;s real name was Frances Ethel Gumm?",
          "correct_answer":"Judy Garland",
          "incorrect_answers":[
             "Doris Day",
             "Julie Andrews",
             "Marilyn Monroe"
          ]
       },
       {
          "category":"Celebrities",
          "type":"multiple",
          "difficulty":"medium",
          "question":"What is the real name of &quot;moot&quot;, founder of the imageboard 4chan?",
          "correct_answer":"Christopher Poole",
          "incorrect_answers":[
             "Mark Zuckerberg",
             "Allison Harvard",
             "Catie Wayne"
          ]
       },
       {
          "category":"Celebrities",
          "type":"multiple",
          "difficulty":"medium",
          "question":"Before voicing Pearl in Steven Universe, Deedee Magno Hall was part of which American band?",
          "correct_answer":"The Party",
          "incorrect_answers":[
             "The Weather Girls",
             "The Pussycat Dolls",
             "The Cheetah Girls"
          ]
       },
       {
          "category":"Celebrities",
          "type":"multiple",
          "difficulty":"medium",
          "question":"Who out of these actresses is the youngest?",
          "correct_answer":"Kiernan Shipka",
          "incorrect_answers":[
             "Ariel Winter",
             "Emma Watson",
             "Bonnie Wright"
          ]
       },
       {
          "category":"Celebrities",
          "type":"multiple",
          "difficulty":"medium",
          "question":"Who is &quot;James Rolfe&quot; better known as?",
          "correct_answer":"The Angry Video Game Nerd",
          "incorrect_answers":[
             "TotalBiscuit",
             "PeanutButterGamer",
             "PewDiePie"
          ]
       }
    ]
 }

javascript simple function won’t pass variable through to identify element id

I can’t understand why the following code won’t work:

function popups(m) {
  var popup = document.getElementById(m);
  popup.classList.toggle("show");
}
.popup {
  position: relative;
  display: inline-block;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.popup .popuptext {
  visibility: hidden;
  width: 160px;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 8px 0;
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  margin-left: -80px;
}

.popup .popuptext::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
}

.popup .show {
  visibility: visible;
  -webkit-animation: fadeIn 1s;
  animation: fadeIn 1s;
}

@keyframes fadeIn {
  from {opacity: 0;}
  to {opacity:1 ;}
}
<div class="popup" onclick="popups(myPopup)">Click me to toggle the popup!
  <span class="popuptext" id="myPopup">A Simple Popup!</span>
</div>

I am pretty sure the error is within the javascript. When I change it to the following then it totally works. So for some reason, it won’t pass my m variable to identify the element id…

function popups() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");
}

Any good coder out there that can help me, please?

How to calculate the screen height and position an element below the fold?

I have a main wrapper with a background image and the background image should extend to cover all of these elements. My HTML looks like this:

<div id="main-wrapper">
    <div id="header"></div>
    <div id="scroll-down-arrow"></div>
    <div class="additional-content"></div>
</div>

I would like the calculate the height of the screen size and position “scroll-down-arrow” at the bottom of the screen and then position “additional-content” below the fold (not viewable area of the screen).

I have read the positioning tutorial here on W3 School: https://www.w3schools.com/Css/css_positioning.asp but still can’t figure out the best way to accomplish this and position the content below the fold while maintaining the background image size of the main-wrapper.

Here’s how my mock-up looks like, let’s say the blue border is the viewable area on the screen, then the elements should be arranged like this:

enter image description here

Preferably I would like this to be pure CSS but I am also open to do the screen height calculation with JS as long as it’s mobile responsive. Can you share a Pen or sample code if you have done something similar to this?

How to strip html tags out of selection

Hi,

I want to strip html tags out of a selected text. Lets say selected text is something like this:

<span style="color:red">some text</span>

So I tried this:

window.getSelection().anchorNode.parentNode.replace(/</?[^>]+>/gi, '');

but I get an error that says replace is not a function. I tried also this below:

window.getSelection().anchorNode.parentNode.remove();

but this will remove also the text. Whats the deal here?

Thank you.

get timezone from an instance of a dayjs object?

I have a util method that takes date input and converts it to dayjs instance with timezone conversion is optional.

import dayjs from 'dayjs';
import timezone from 'dayjs/plugin/timezone';
import utc from 'dayjs/plugin/utc';

const convertDateToLocalFormat= (date = dayjs(), isTimezoneConvesrionRequired = true)=>{
  
  dayjs.extend(utc);
  dayjs.extend(timezone);
  if(isTimezoneConvesrionRequired){
   const tZone = dayjs.tz().guess();
   return dayjs(date).tz(tZone);
  }
  return dayjs(date);

}

**
The problem:
**
Now if I pass an instance of daysjs object to this function, for which already timezone is applied(in the first iteration), I am getting a date which has two times timezone applied.
For example, I am Pacific time zone(browser timezone, let’s say 9 am, Feb 5th, 2022). My target time zone is India (I am getting this timezone from my database). So Instead of getting 10.30 pm, Feb 5th, 2022 I am getting 12 am, Feb 6th, 2022.

**
My approach:
**
If there is a way to get timezone info from a dayjs object, I can check whether the timezone is the same. Something like this.

const instanceTimeZone = date.getTimeZoneInfo() // assuming date is already an instance 
                                               // of dayjs and getTimeZoneInfo() is what 
                                               // I am looking for, some util kind of 
                                               // method
if(isTimezoneConvesrionRequired && instanceTimeZone !== dayjs.tz().guess() ){
   const tZone = dayjs.tz().guess();
   return dayjs(date).tz(tZone);
  }

Where to put session_write_close()

I have issue in my website, it causing 500 iternal server error. someone said it is about session. I’m using codeigiter 4. After I look at ci4 documentation about session, it is said that if I have website with heavy usage of AJAX and having performance issue, I have to use session_write_close().

My question is, where to put this session_write_close()? Is it:

a. In every function at every controller.

b. In layout view is enough (the layout view is the one that contain header, footer, and side navigation).

c. After accessing session (be it getting session data or upadatig it).

d. Only after updating session data.

e. None of the above.

Please help.
Thanks.

Resize Image Application

I’d like to be able to allow a user to select an image from their computer and my program will resize it so that it fits within a certain range. In many social media apps, you have a frame so you can select a part of the image that will become your profile image. I want to do something similar but I don’t know where to start. Could anyone give me any assistance in what I should be thinking about or where to look for information. I’m currently learning javascript and php so preferably in those languages

Why my code is showing “Invalid regular expression: missing /” error?

I was trying to create a simple chat-room using express and socket.io but I encountered with an error while running the server. Can someone help?

Server.js

const express = require("express");
const path = require("path");

const app = express();
const server = require("http").createServer(app);

const io = require("socket.io")(server);

app.use(express.static(path.join(__dirname+"/public")));

io.on("connection", function(socket){
    socket.on("newuser",function(username){
        socket.broadcast.emit("update", username + " joined the conversation");
    });
    socket.on("exituser",function(username){
        socket.broadcast.emit("update", username + " left the conversation");
    });
    socket.on("chat",function(message){
        socket.broadcast.emit("chat", message);
    });
});

server.listen(5000);

After entering node server.js on the command prompt I see this error

Error Message:
app.use(express.static(path.join(__dirname*/public)));
^

SyntaxError: Invalid regular expression: missing /
    at wrapSafe (internal/modules/cjs/loader.js:1001:16)
    at Module._compile (internal/modules/cjs/loader.js:1049:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
    at internal/main/run_main_module.js:17:47

Redirect to another page on the div with active class

I have two HTML pages. The first page(index1.html) has two buttons: Get Started and Login. The second page (index2.html) is a double slider page with two divs: Sign-in div with login form and Sign-up div with register form, where only one of them is shown one at a time and if a button is clicked, the other div is shown and set as active. The default active div is the Sign-up div/form, so in my HTML file, the sign-up div is already set to active: <div class="form sign-up-form active">...</div>, while my sign-in div is not <div class="form sign-in-form">...</div>

index2.html sign up

index2.html sign in

The jquery buttons that adds active class on my Sign-in and Sign up forms:

signIn_button.addEventListener('click', () => {
    overlay_container.style.transform = 'translateX(100%)';
    overlay.style.transform = 'translateX(-50%)';

    signIn_form.classList.add('active');
    signUp_form.classList.remove('active');
})

signUp_button.addEventListener('click', () => {
    overlay_container.style.transform = 'translateX(0)';
    overlay.style.transform = 'translateX(0)';

    signUp_form.classList.add('active');
    signIn_form.classList.remove('active');
})

I want my button Get Started: <button class="get_started">Get Started</button> in index1.html to redirect to index2.html but on active Sign-Up form: <div class="form sign-up-form active">...</div>

and my button Login: <button class="login">Login</button> in index1.html to redirect to index2.html but on active Sign-In form: <div class="form sign-in-form">...</div>

The problem is I can’t redirect them to the specific active div. Both buttons currently only redirect to the default active div, which is Sign-up div.