I want to change the HTML dynamically using java script after submitting form to PHP

THis My PHP code

<?php


//Include libraries
require __DIR__ . '/vendor/autoload.php';
    
//Create instance of MongoDB client
$mongoClient = (new MongoDBClient);

//Select a database
$db = $mongoClient->EcommerceWeb;

//Select a collection 
$collection = $db->Employees_Data;

//Extract the data that was sent to the server
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);


 

$findemail = [
"email" => $email, 
"password" => $password, 
];

$cursor = $collection->findOne($findemail);
if($cursor){
    if($cursor['email'] == $email and $cursor['password'] == $password){ 
        echo("<script>alert('User Successfully Added')</script>");
        echo("<script>window.location = 'cms-view-products.html'</script>");
    }
}
else {
    echo("<script> alert('failed login') </script>");
    echo("<script>  window.location = 'login.html'</script>");  
}

  ?>

AND this is my HTML code

<?php include('login.php') ?>
<!DOCTYPE html>


<html>
    <head>
        <title>LogIn Demo</title>
    </head>
  
    <body>
        <form action="login.php"  method="post" >
            Email: <input type="email" name="email" required >
            Password: <input type="password" name="password" required >
            <input type="submit">
           <p id="feedback"></p>  
        </form>

</body>
    
  
</html>

What I want to do and what I have tried

I have tried to echo the massage by echoing JS code to change the innerHTML element

but didn’t work.

I tried to echo the massage using PHP which works for me but I can’t use echo then header to redirect to a different page in PHP, and I found something the $Session to solve the problem.

My question
Is there a way to use JS better than alert to produce a massage then redirect to another page in successful login OR stay on the same page if the login failed?

React ) How to access specific object in the list for save the useState

https://codesandbox.io/s/warehouse-shop-managing-system-5w9b3?file=/src/App.js

I’m making a dialog that automatically stores the inventory of the warehouse.

{
  "area1": {
    "warehouse": [
      { "type": "coffee", "quantity": "1000" },
      { "type": "beef", "quantity": "200" },
      { "type": "sugar", "quantity": "750" }
    ],
    "shop": [
      { "type": "coffee", "quantity": "15" },
      { "type": "beef", "quantity": "3" },
      { "type": "sugar", "quantity": "90" }
    ]
  }
}

Q1) There are two objects in the list. How can I store it in the list sequentially using forEach, map, etc?

(ReactHooks or ClassComponent)

  function autoLoad() {
    db.area1.warehouse.forEach(
      (item) => {
        setInputType(...inputType, item.type);
        setInputQuantity(...inputQuantity, item.quantity);
      },
      setItemList([
        ...itemList,
        {
          itemType: "warehouse",
          itemId: Date.now()
        }
      ])
    );
  }

Q2) I want to delete it only when I press the Hide_button and finally press the Final_Save button.

For example, you can’t see it in the dialog by pressing the DELETE button, but if you press the cancel button, it won’t be deleted. And if you open the dialog again, you can see the added items.

Is it right to make a separate list for deletion and a list for hiding?
or using Callback?

 const renderItemList = itemList.length
    ? itemList.map((item) => {
        return (
          <>
            <div>
              <div style={{ height: "60px" }}>
                <TextField
                  value={item.inputType}
                  type="text"
                  style={{ marginBottom: "30px" }}
                />
              </div>
              <div style={{ height: "60px" }}>
                <TextField
                  value={item.inputQuantity}
                  type="text"
                  style={{ marginBottom: "30px" }}
                />
              </div>

              <div>{hideButton(item)}</div>
            </div>
          </>
        );
      })
    : "";

  function hideButton(item) {
    return (
      <Button
        onClick={() => removeItemInList(item.itemId)}
        style={{
          backgroundColor: "#2db7e2",
          fontSize: "14px",
          marginBottom: "30px"
        }}
      >
        {"Hide_Item"}
      </Button>
    );
  }
  const removeItemInList = (itemId) => {
    setItemList(
      itemList.filter((item) => {
        return item.itemId !== itemId;
      })
    );
  };
import "./styles.css";
import {
  TextField,
  Tooltip,
  MuiButton,
  Button,
  Dialog,
  DialogContent,
  DialogActions
} from "@material-ui/core";
import React, { useState, useRef, useEffect } from "react";
import { Map, List } from "immutable";
import db from "./db.json";

export default function App() {
  const [showDialog, setShowDialog] = useState(false);
  const [inputType, setInputType] = useState("");
  const [inputQuantity, setInputQuantity] = useState("");
  const [itemList, setItemList] = useState([]);
  const [jsonData, setJsonData] = useState({});

  useEffect(() => {
    setJsonData(db);
    autoLoad();
    console.log("itemList:", itemList);
  }, []);

  function autoLoad() {
    db.area1.warehouse.forEach(
      (item) => {
        setInputType(...inputType, item.type);
        setInputQuantity(...inputQuantity, item.quantity);
      },
      setItemList([
        ...itemList,
        {
          itemType: "warehouse",
          itemId: Date.now()
        }
      ])
    );
  }

  function resetForm() {
    setInputType("");
    setInputQuantity("");
  }

  function addList(e) {
    e.preventDefault();
    setItemList([
      ...itemList,
      {
        itemType: "shop",
        itemId: Date.now(),
        inputType: inputType,
        inputQuantity: inputQuantity
      }
    ]);
    resetForm();
  }

  const renderItemList = itemList.length
    ? itemList.map((item) => {
        return (
          <>
            <div>
              <div style={{ height: "60px" }}>
                <TextField
                  value={item.inputType}
                  type="text"
                  style={{ marginBottom: "30px" }}
                />
              </div>
              <div style={{ height: "60px" }}>
                <TextField
                  value={item.inputQuantity}
                  type="text"
                  style={{ marginBottom: "30px" }}
                />
              </div>

              <div>{hideButton(item)}</div>
            </div>
          </>
        );
      })
    : "";

  function openDialog() {
    setShowDialog(!showDialog);
  }

  function onDismiss() {
    setShowDialog(false);
    setInputType("");
    setInputQuantity("");
  }

  const removeItemInList = (itemId) => {
    setItemList(
      itemList.filter((item) => {
        return item.itemId !== itemId;
      })
    );
  };

  function hideButton(item) {
    return (
      <Button
        onClick={() => removeItemInList(item.itemId)}
        style={{
          backgroundColor: "#2db7e2",
          fontSize: "14px",
          marginBottom: "30px"
        }}
      >
        {"Hide_Item"}
      </Button>
    );
  }

  function onSubmit() {}

  return (
    <>
      <Button onClick={openDialog} style={{ backgroundColor: "#4cb7f3" }}>
        {"Here"}
      </Button>
      <Dialog open={showDialog} onClose={onDismiss}>
        <div
          className="App"
          style={{ height: "500px", width: "500px", alignItems: "center" }}
        >
          {renderItemList}
          <div style={{ height: "100px" }}>
            <TextField
              type="text"
              // value={}
              placeholder="Please, Input the Type"
              onChange={(e) => setInputType(e.target.value)}
              style={{ marginTop: "30px", marginBottom: "30px" }}
            />
          </div>
          <div style={{ height: "60px" }}>
            <TextField
              type="text"
              // value={inputQuantity}
              placeholder="Please, Input theQuantity"
              onChange={(e) => setInputQuantity(e.target.value)}
              style={{ marginBottom: "30px" }}
            />
          </div>
          <div style={{ height: "40px" }}>
            <Button
              type="submit"
              onClick={addList}
              style={{ backgroundColor: "#fc7090", fontSize: "14px" }}
            >
              {"add"}
            </Button>
            <br />
            <br />
            <Button
              type="submit"
              onClick={onSubmit}
              style={{ backgroundColor: "#80cbc4", fontSize: "14px" }}
            >
              {"final_save"}
            </Button>
          </div>
        </div>
      </Dialog>
    </>
  );
}

how to change button class when i click on it using Jquery?

so I am using Jquery to try and change bootstrap buttons classes when I click on them using the toggleClass but the problem is I only can toggle between only 2 classes and that not what I want, I want to toggle between at least 5 classes or even more each time I click on the button, but I can’t find a way to do it

<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8" />
    <title>toggle</title>
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
    />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>
  <script>
    $(document).ready(function () {
      $("button").click(function () {
        $(this).toggleClass("btn btn-success btn btn-info btn btn-primary");
      });
    });
  </script>
  <style>
    #p {
      position: absolute;
      top: 50%;
      left: 50%;
    }
  </style>
  <body>
    <button id="p" class="btn btn-success">Random button</button>
  </body>
</html>

I get this error: Cannot read properties of undefined (reading ‘send’) when I run the command I made, What do I do?

So I am trying to make an embed rules message for my server and I get an error saying “Cannot read properties of undefined (reading ‘send’)”.

The code:

const message = require("../events/guild/message")
const { MessageEmbed } = require('discord.js')

module.exports = {
    name: 'spawnrules',
    description: "Spawn the server rules",
    execute(message, args, Discord, client) {
        const rules = new MessageEmbed()
        .setColor('LIME')
        .setTitle('Rules')
        .setDescription('These are the server rules, Make sure to follow them to avoid being punished.')
        .addFields(
            {name: '1'},
            {name: 'Do not be racist', value: '2'},
            {name: '2'},
            {name: '3'},
            {name: 'No NSFW', value: 'NSFW is forbidden in our server. NSFW will result in a discord report and a permanent ban.'},
        )
        .setFooter('32')
        message.channel.send(rules)
    }
}

Error:

        message.channel.send(rules)
                        ^

TypeError: Cannot read properties of undefined (reading 'send')
    at Object.execute (C:TeamsTeam LapisLapis Botcommandsspawnrules.js:20:25)
    at module.exports (C:TeamsTeam LapisLapis Boteventsguildmessage.js:9:25)
    at Client.emit (node:events:520:28)
    at MessageCreateAction.handle (C:TeamsTeam LapisLapis Botnode_modulesdiscord.jssrcclientactionsMessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (C:TeamsTeam LapisLapis Botnode_modulesdiscord.jssrcclientwebsockethandlersMESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (C:TeamsTeam LapisLapis Botnode_modulesdiscord.jssrcclientwebsocketWebSocketManager.js:384:31)
    at WebSocketShard.onPacket (C:TeamsTeam LapisLapis Botnode_modulesdiscord.jssrcclientwebsocketWebSocketShard.js:444:22)
    at WebSocketShard.onMessage (C:TeamsTeam LapisLapis Botnode_modulesdiscord.jssrcclientwebsocketWebSocketShard.js:301:10)
    at WebSocket.onMessage (C:TeamsTeam LapisLapis Botnode_moduleswslibevent-target.js:132:16)
    at WebSocket.emit (node:events:520:28)

I’d appreciate it if someone will help 🙂

How to make a select option dropdown with objects? Javascript and HTML

I’m trying to make a select option dropdown in javascript and write it in HTML. The options are placed in an object in javascript (under “valg”). I have tried different solutions but, I can’t get it to work properly. Do you have any ideas?

The code is here:


let produkter = [
            {
            navn: 'Eple',
            pris: 20,
            beskrivelse: 'Smakfullt og sunt.',
            bilde: '<img id="bilde" src="../bilder/iphone.jpeg">',
            valg: ['Grønt', 'Rødt', 'Gult'],
            antall: 0 
        },
            {
            navn: 'Banan',
            pris: 15,
            beskrivelse: 'Gult og kult.',
            bilde: '<img id="bilde" src="../bilder/iphone.jpeg">',
            valg: ['SmĂĄ', 'Store'],
            antall: 0 
        },
            {
            navn: 'Pære',
            pris: 12,
            beskrivelse: 'Alltid en pære til lunsj.',
            bilde: '<img id="bilde" src="../bilder/iphone.jpeg">',
            valg: ['SmĂĄ', 'Store'],
            antall: 0 
        },
            {
            navn: 'Sitron',
            pris: 14,
            beskrivelse: 'Sitron er godt.',
            bilde: '<img id="bilde" src="../bilder/iphone.jpeg">',
            valg: ['Moden', 'Ikke moden'],
            antall: 0 
        }
        ]

        
        
        for (var i = 0; i < produkter.length; i++) {
            let bodyEl = document.querySelector("body");
            bodyEl.id = "bodydiv";
            let hovedEl = document.createElement("div");
            hovedEl.id = "hoved";
            bodyEl.appendChild(hovedEl);



            let h2El = document.createElement("h2");
            h2El.id = "navn"
            h2El.innerHTML = produkter[i].navn;
            hovedEl.appendChild(h2El);

            let bildeEl = document.createElement("p");
            bildeEl.innerHTML = produkter[i].bilde;
            hovedEl.appendChild(bildeEl);

            let avsnittEl = document.createElement("p");
            avsnittEl.id = "beskrivelse";
            avsnittEl.innerHTML = produkter[i].beskrivelse;
            hovedEl.appendChild(avsnittEl);

            let prisEl = document.createElement("p");
            prisEl.innerHTML = 'kr. ' + produkter[i].pris;
            hovedEl.appendChild(prisEl);

            let antallEl = document.createElement("input");
            antallEl.type = "number";
            antallEl.id = "antall"
            hovedEl.appendChild(antallEl);

            let knappEl = document.createElement("button");
            knappEl.innerHTML = "Kjøp";
            knappEl.id = "knapp";
            hovedEl.appendChild(knappEl);
            knappEl.onclick = function() {
                alert('Knapp er trykket pĂĄ');
            }


            // Here I'm trying to make the select option dropdown

            let flervalgEl = document.createElement("select");
            flervalgEl.innerHTML = produkter[i].valg;
            hovedEl.appendChild(flervalgEl);

            let valgAltEl = document.createElement("option");
            valgAltEl.innerHTML = produkter[i].valg[i];
            flervalgEl.appendChild(valgAltEl);

                    
        }

It’s the last part of the code that I’m struggling with. Under the comment.

Authenticate microsoft account to firebase website only, and not other microsoft services

I am using firebase for a website, where users can sign in with their microsoft accounts:

import {getAuth, signInWithRedirect, OAuthProvider} from "firebase/auth";

(...)

const provider = new OAuthProvider('microsoft.com');
const auth = getAuth();
signInWithRedirect(auth, provider);

I have managed to make everything work nicely, except one detail:
When I sign in with the Microsoft account in the webbrowser for the firebase site, I am also signed in to my complete Office 365 account in the background (and probably other mirosoft sites).

So if I go to the website for my Outlook 365 online mail, then I am already logged in since I logged into my firebase project.

How can I limit the microsoft sign-in to only authenticate in the firebase project, and nothing else?

ReactJs – Sort method

I have a table in my react app and it gets its data from API.

I want to sort one of its columns. a[obj1][obj2] or b[obj1][obj2] Usually is a string of numbers and sometimes are equal to "-" (Dash)
this is my sort function:

if (order === "DEF") {
  const sorted = props.currency.sort((a, b) =>
    Number(a[obj1][obj2]) > Number(b[obj1][obj2])
      ? 1
      : Number(b[obj1][obj2]) > Number(a[obj1][obj2]) || a[obj1][obj2] === "-"
      ? -1
      : 0
  );
  props.setCurrency(sorted);
  setOrder("ASC");
} else if (order === "ASC") {
  const sorted = props.currency.sort((a, b) =>
    Number(a[obj1][obj2]) < Number(b[obj1][obj2]) || a[obj1][obj2] === "-"
      ? 1
      : Number(b[obj1][obj2]) < Number(a[obj1][obj2])
      ? -1
      : 0
  );
  props.setCurrency(sorted);
  setOrder("DSC");
} else {
  const sorted = defaultCurrency;
  props.setCurrency(sorted);
  setOrder("DEF");
}

After the sort is called I want to behave with "-" like a zero,
but the items which are equal to "-"are always placed on the top of the table when the order is equal to ASC or DSC, while the other items of the array are sorted correctly.

Chart JS tick options not working for y axis

I have been struggling to make a chart.js line chart start at 0 when all of the values are 0. If all of the data of a dataset is 0 the y axis will always show values below 0 which I don’t want there.

Here is the example:

    <canvas id="lineChart"></canvas>
    <script>
        var ctx = document.getElementById('lineChart');
        var lineChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: [1,2,3],
                datasets: [{
                    data: [0, 0, 0]
                }]
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        ticks: {
                            beginAtZero:true
                        }
                    }
                }
            }
        });
    </script>
<div>```

As you can see I am changing in the options the scales as suggested in the documentation [here][1] (apparently there has been a migration and this is the way to go in v3, which is what I am using). But the graph still won't start at 0:
[![chart example][2]][2]

Any axis options other than the ticks work correctly. I have also tried 
Any ideas of what I might be doing wrong? 


  [1]: https://www.chartjs.org/docs/master/getting-started/v3-migration.html#scales
  [2]: https://i.stack.imgur.com/9IWmc.png

Add newline after each key, value using JSON.stringify()

I want to add a newline after each key value pair in an object using JSON.stringify()

In my actual code I will be getting a lot of key value pairs and having the new lines makes it easier to read.

Example code is:

let test = {'key' : ['one', 'two', 'three'], 'keyTwo' : ['one', 'two', 'three']}

let testOne = JSON.stringify(test, null, 't')

console.log(testOne)

outputs:
{
        "key": [
                "one",
                "two",
                "three"
        ],
        "keyTwo": [
                "one",
                "two",
                "three"
        ]
}

I want:
{
        "key": [
                "one",
                "two",
                "three"
        ],
                                   <----- newline here
        "keyTwo": [
                "one",
                "two",
                "three"
        ]
}

I have tried

let test = {'key' : ['one', 'two', 'three'] + "\n", 'keyTwo' : ['one', 'two', 'three']+ "\n"}

let testOne = JSON.stringify(test, null, 'tn')
console.log(testOne);

Neither work

jquery file not found

<script src="jquery.js"></script>
<html>

<head>
<meta charset="UTF-8">
<!--<script type="text/javascript" charset="UTF-8" src="jquery.js"></script>-->
<script type="text/javascript">
    function sendd() {
        var firstname = $("#firstname").val();
        var lastname = $("#lastname").val();
        if ($.trim(firstname).length > 0 & $.trim(lastname).length > 0) {
            $.ajax({
                type: "POST", //Request type
                url: "http: /localhost/firstname.php",
                data: {
                    firstname: firstname,
                    lastname: lastname
                },
                cache: false,
                success: function(data) {
                    alert(data);
                }
            })
        } else {
            alert("Input fields are empty");
        }
    }
</script>
</head>

<body>
    
    <input type=”text” placeholder=”write your first name” id=”firstname”>
    <input type=”text” placeholder=”write your last name” id=”lastname”>
    <button id="sub" onclick="sendd()">Submit result</button>
</body>

</html>

error:
GET file:///C:/Users/kalat/Documents/random%20projects%20c++%20or%20py%20or%20phpor%20html%20or%20css/android/Hello/www/jquery.js net::ERR_FILE_NOT_FOUND

Button type submit – How to validate first

I have a form with a submit button. I can not change it and anything about the html.

<form> 
<input type="text" class="form-control" id="username" required>
<label for="username">Username</label>
<input type="password" class="form-control" id="password" required>
<label for="password">Password</label>
<button id="submit" class="btn btn-lg" type="submit">Sign in</button>
<form> 

This is my js:

let nombre = document.getElementById("username").value;
let pass = document.getElementById("password").value;

    async function login() {    
       try{  
            const response = await fetch('http://localhost:8888/login', {          
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({"username": nombre, "password": pass})
            });
            if(response.status !== 200) throw response.statusText;
            const content = await response.json();
            return content;
    
       } catch (error){console.log("Errorr:" + error);}
       }
    
    
    
    function submit() {    
        let validacion1 = document.getElementById('username').checkValidity();
        let validacion2 = document.getElementById('pass').checkValidity();
        if (validacion1 == true && validacion2 == true){
        login();
       }     
      }


document.getElementById('submit').addEventListener('click', submit);

But if I click in my submit button, the page “recharge” and I can not do the login properly.

I should click the submit button and wait for the username and password to be correct.

How can I click the submit button and not instant recharge the page?

Thank you so much

Why am I having this kind of error .Warning: validateDOMNesting(…): cannot appear as a descendant of

i’m creating big project with React js/Redux, smth like social media app. I don’t know from where, however I got the error index.js:1 Warning: validateDOMNesting(...): <a> cannot appear as a descendant of <a>. at a. I don’t know how to solve that, because it is not showing where the error is. I have changed all my -s to NavLink, but the error didn’t solved. Help me if you can.

enter image description here

Should I deep copy when modifying nested object?

I recently started learning functional programming in Javascript, and one thing that’s valued is Immutability. One way to preserve immutability is to when we want to modify some object that we first create a copy and then modify that copy and return it, for example:

const person = {
    firstName: 'John',
    lastName: 'Smith',
}

const modifyFName = obj => {
    const objCopy = {...obj};
    objCopy.firstName = 'James';
    return objCopy;
}

console.log(modifyFName(person)) // {firstName: 'James', lastName: 'Smith'}
console.log(person) // {firstName: 'John', lastName: 'Smith'}

But if I want to modify some deeply nested object creating shallow copy like one above wouldn’t make much of a difference, for example:

const person = {
    firstName: 'John',
    lastName: 'Smith',
    parents: {
        mom: {
            firstName: 'Jennifer',
            lastName: "Swift"
        },
        dad: {
            firstName: 'Tom',
            lastName: 'Cartman'
        }
    }
}

const modifyDadName = obj => {
    const objCopy = {...obj};
    objCopy.parents.dad.firstName = 'Aurelion';
    return objCopy;
}

console.log(modifyDadName(person)) // {... dad: "Aurelion"}
console.log(person) // {... dad: "Aurelion"}

Both objects have changed. So I am wondering in this situation should I perhaps use deep copy, or maybe use some third-party Immutable data structures, or is there some other solution for this?

How to run several js files at once?

I’ve created simple tool that I would like to work daily to get new data everyday. I have few js files that I would like to run at once. Instead of manually typing in terminal:

node news.js 
node main.js
node weather.js

Can I automate it somehow to type one command and everything runs automatically when previous file finished task?

Thanks

ReactJS – Get Elements from iFrame on Hover

Hi I have a Reac/NextJS page which looks like this:

import Layout from "@/components/app/Layout";
import Sidebar from "@/components/app/Sidebar";

export default function SiteIndex() {
  return (
    <Layout>
      <div className="flex">
        <Sidebar />
        <div className="m-5">
            <iframe src="/page.htm"></iframe>
        </div>
      </div>

    </Layout>
  );
}

It has an iframe included inside it.

What I need is that when the user hovers over any HTML element in the iframe, I want to do the following:

  1. Highlight that element on the screen,
  2. Display the contents of that in the sidebar.
  3. Make that element editable. it doesn’t have to be saved. But just editable.

Is it possible to do? How can we achieve that using reactjs/javascript?

Not sure if this is relevant but say if the nextjs project is on example.com, the iframe is coming from test.example.com. I have access to both domains/projects.