I have an issue with mysql route , the browser hangs/pending after executing the query , though i have used end() method

I have an issue with the MySQL route, After executing the MySQL query, the browser waiting/pending for something, though I have used the connection.end() method

I have checked the database, the data was successfully stored, I need to execute second part of the code after the SQL query

route.js

app.post('/data',(req,res)=>{


  let sql = 'INSERT INTO `data` (`name`) VALUES (?)'
  connection.query(sql,req.body.name,(err,result)=>{

    if(err) throw err
    console.log ( 'value inserted')
    connection.end()

  })
  
})

I want to execute the following code after the connection close

    var text = document.querySelector("input").value;
    var node = document.createElement("p");
    
   
    if (text!=""){
                    var textnode=document.createTextNode(text);
                    node.appendChild(textnode); //append the value to LI  
                    text = document.getElementById("demo")//  " demo " is the Un-order list id
                    console.log(text) ;
                    document.getElementById("demo").appendChild(node); //append the value to UI
                    document.querySelector("input").value = ""
 
                   
                }
    
}  

i have a code that its kinda dirty and i cant think of a way to improve it, what can i do to have a more compact and better solution?

I’m trying to get a specific result of my database in mongoose, but this is what i have its working but the code looks pretty bad.

 const completedOrders = await Order.find({ "status": "delivered" }).
    populate('address');

the response of the database is this and i trying to get all the states of every order with status: “delivered”

"completedOrders": [
    {
        "_id": "61b81eef631dcc413e98515a",
        "user": "61b51dcbfd50717dc6dc931a",
        "address": {
            "address": {
                "phone": 54156345645768,
                "rut": "26.232.966-6",
                "state": "metropolitana",
                "city": "dunno",
                "province": "pepe",
                "street": "asdaqqqqqqqda",
                "numstreet": 999
            },
            "_id": "61b8179e7dfc15f26c561175",
            "user": "61b51dcbfd50717dc6dc931a",
            "__v": 0
        },
        "status": "delivered",
        "orderItems": [
            "61b81ee6631dcc413e985146",
            "61b81ee6631dcc413e985147"
        ],
        "shipping": 3500,
        "code": "c986aeb3-1fc9-422e-8638-b40651d7906c",
        "total": 690,
        "totalCost": 370,
        "createdAt": "2021-12-14T04:34:55.564Z",
        "updatedAt": "2021-12-14T04:34:55.564Z"
    },
    {
        "_id": "61b81fddda2eb87de7d44c42",
        "user": "61b51dcbfd50717dc6dc931a",
        "address": {
            "address": {
                "phone": 54156345645768,
                "rut": "26.232.966-6",
                "state": "metropolitana",
                "city": "dunno",
                "province": "pepe",
                "street": "asdaqqqqqqqda",
                "numstreet": 999
            },
            "_id": "61b8179e7dfc15f26c561175",
            "user": "61b51dcbfd50717dc6dc931a",
            "__v": 0
        },
        "status": "delivered",
        "orderItems": [
            "61b81fdbda2eb87de7d44c32",
            "61b81fdbda2eb87de7d44c33"
        ],
        "shipping": 3500,
        "code": "e2828a65-ea12-43e9-9909-f081c9cd32e9",
        "total": 690,
        "totalCost": 370,
        "createdAt": "2021-12-14T04:38:53.517Z",
        "updatedAt": "2021-12-14T04:38:53.517Z"
    }
]

so this is what i tried but its quite dirty and i still want to do the same for city, and provinces, is for the analitycs of my ecommerce

    const AddressesUser = await Promise.all(completedOrders.map(async (array) => {
        const allAddresses = array.address;
        return allAddresses;
    }));

    const arrayAddresses = await Promise.all(AddressesUser.map(async (array) => {
        const allAddresses = array.address;
        return allAddresses;
    }));

    
    const allStates = await Promise.all(arrayAddresses.map(async (array) => {
        const states = array.state;
        return states;
    }));

How to keep current url including parameters in JavaScript

I am using the modal to edit data by using the code below, and when I click the ‘Change’ button,
I want to keep the current url. Even when I set a parameter, I don’t want me to lose the parameter.

This url has no parameters set. So, if I edit data in modal and click the ‘change’ button, I lose all the parameters I set and return to the initialized screen.

I am using Django and python, and I am getting parameter values ​​through request.POST.get method in views.py .

function (data, status, xhr) {
            let code = data.code
            if (code === 'error') {
                for (let i in fields) {
                    let key = fields[i];
                    let labelElement = editForm.find('label[for=' + key + ']');
                    let container = labelElement.parent();

                    if (key in data.error) {
                        container.addClass('card-inverse-danger');
                        const msg = data.error[key][0];
                        let text = $('<div class="text-danger small" style="line-height: 1rem;">' + msg + '</div>')
                        labelElement.find('.text-danger').remove();
                        labelElement.append(text);
                    } else {
                        container.removeClass('card-inverse-danger');
                        labelElement.find('.text-danger').remove();
                    }
                }
            } else if (code === 'success') {
                window.location.href = '/study/help/'; --> I think I need to update this line.
            }
        })

Cannot read properties of undefined (reading ‘split’) React.js

I am building a react app and when I try to load up the application in the browser, I get the error in the title. Command I am using to start the application : swa start http://localhost:3000 –run “npm start –javascript” –api-location src/api. Looking through the stack trace this seems to be related to a line in the Mongoose browser.umd file that is trying to split t.versions.node :

e.noop=function(){},e.errorToPOJO=function(t){if(!(t instanceof Error))throw new Error(“error must be instanceof Error.”);var e,r={},o=n(Object.getOwnPropertyNames(t));try{for(o.s();!(e=o.n()).done;){var i=e.value;r[i]=t[i]}}catch(t){o.e(t)}finally{o.f()}return r},e.nodeMajorVersion=parseInt(t.versions.node.split(“.”)[0],10)}).call(this,r(10))},function(t,e,r){“use strict”;(function(t){

This is not my code and I am unsure exactly what it is doing or why the t.versions.node is undefined. My node version is 14.16.1, mongoose version is 5.11.1. Stack trace included below :

Uncaught TypeError: Cannot read properties of undefined (reading 'split')
    at Object.<anonymous> (browser.umd.js:220)
    at Object.<anonymous> (browser.umd.js:220)
    at r (browser.umd.js:1)
    at Object.<anonymous> (browser.umd.js:1012)
    at r (browser.umd.js:1)
    at Object.<anonymous> (browser.umd.js:1009)
    at r (browser.umd.js:1)
    at Object.<anonymous> (browser.umd.js:308)
    at Object.<anonymous> (browser.umd.js:425)
    at r (browser.umd.js:1)
    at Object.<anonymous> (browser.umd.js:756)
    at r (browser.umd.js:1)
    at Object.<anonymous> (browser.umd.js:973)
    at Object.<anonymous> (browser.umd.js:977)
    at r (browser.umd.js:1)
    at Object.<anonymous> (browser.umd.js:973)
    at r (browser.umd.js:1)
    at browser.umd.js:1
    at browser.umd.js:1
    at browser.umd.js:1
    at Object../node_modules/mongoose/dist/browser.umd.js (browser.umd.js:1)
    at __webpack_require__ (bootstrap:856)
    at fn (bootstrap:150)
    at Module.<anonymous> (App.js:38)
    at Module../src/api/app_functions/func_mongo_create_connection.js (func_mongo_create_connection.js:132)
    at __webpack_require__ (bootstrap:856)
    at fn (bootstrap:150)
    at Module../src/api/az_func_wfd/index.mjs (index.mjs:1)
    at __webpack_require__ (bootstrap:856)
    at fn (bootstrap:150)
    at Module.<anonymous> (CollectLoginInfo.js:59)
    at Module../src/component/Configuration.js (Configuration.js:368)
    at __webpack_require__ (bootstrap:856)
    at fn (bootstrap:150)
    at Module.<anonymous> (App.css?dde5:82)
    at Module../src/App.js (App.js:38)
    at __webpack_require__ (bootstrap:856)
    at fn (bootstrap:150)
    at Module.<anonymous> (index.css?bb0a:82)
    at Module../src/index.js (index.js:18)
    at __webpack_require__ (bootstrap:856)
    at fn (bootstrap:150)
    at Object.1 (ui_carmax_logo.PNG:1)
    at __webpack_require__ (bootstrap:856)
    at checkDeferredModules (bootstrap:45)
    at Array.webpackJsonpCallback [as push] (bootstrap:32)
    at main.chunk.js:1

I also believe this might have something to do with my import/exports of functions throughout my code, but that is partially a guess. Any help is appreciated.

Assign ref dynamically inside concat in react render

I have an array of objects which I create on pressing the add button.The add handler function is as below.

const [inputList,setInputList] = useState([])

const elref=useRef(null)

const add = () => {
setInputList([...inputList,
<div>
<EditContainer

onTextChnage={handleChange}
ref={elref}
/>

</div>
}])}

This create multiple EditContainer elements all of which share the same ref.How can I create refs like this on the fly for a dynamic array of Object which is a state

Don’t have permission to read data on Onclick in React Firebase Firestore

I am creating a button that loads more documents from firestore database but the problem arises that I am able to do it in useEffect and set the state to the data. When I try to do the same thing in on click event handler it gives me the error that you don’t have sufficient access as I am logged in I have the access so I was able to get the data from firestore.
Here is some code::

import React, { useEffect, useState } from "react";
import Container from "@mui/material/Container";
import Box from "@mui/material/Box";
import Typography from "../../subcomponents/Typography";
import Adcard from "../../subcomponents/Marketplace/Adcard";
import Button from "@mui/material/Button";
import Pagination from "../../subcomponents/Marketplace/PaginationComponent";
import { db } from "../../config/Config";

function Adspace({ Products }) {
  const [data, setData] = useState(null);
  const [lastDoc, setlastDoc] = useState();
  useEffect(() => {
    return db
      .collection("Products")
      .orderBy("MonthlyRate", "asc")
      .limit(2)
      .get()
      .then((snapshot) => {
        const ProductData = snapshot.docs.map((doc) => doc.data());
        /* snapshot.docs.forEach((doc) => {
          ProductData.push({ ...doc.data(), id: doc.id });
          setData(ProductData);
        }); */
        setData(ProductData);

        const lastDoc = snapshot.docs[snapshot.docs.length - 1];
        setlastDoc(lastDoc);
      });
  }, []);
  console.log(data);
  console.log(Products);
  const fetchData = () => {
    db.collection(Products)
      .orderBy("MonthlyRate", "asc")
      .startAfter(lastDoc)
      .limit(1)
      .get()
      .then((snapshot) => {
        const ProductData = snapshot.docs.map((doc) => doc.data());
        setData((PrevData) => [...PrevData, ProductData]);
        const lastDoc = snapshot.docs[snapshot.docs.length - 1];
        setlastDoc(lastDoc);
      });
  };
  return (
    <div>
      <Container component="section" sx={{ mt: 8, mb: 4 }}>
        <Typography variant="h4" marked="center" align="center" component="h2">
          Rent Machines
        </Typography>
      </Container>
      <Box
        sx={{
          m: 8,
          display: "flex",
          flexWrap: "wrap",
          justifyContent: "flex-start",
        }}
      ></Box>
      <Container
        component="section"
        sx={{ mt: 8, mb: 4, display: "flex", justifyContent: "center" }}
      >
        {/*  {data !== null ? <Adcard /> : ""} */}

        {data !== null
          ? data.map((doc) => {
              if (doc.Type === Products) {
                return <Adcard data={doc} state={Products} key={doc.id} />;
              } else if (Products === "All") {
                return <Adcard data={doc} state={Products} />;
              }
            })
          : ""}
      </Container>
      <Box textAlign="center">
        <Button variant="contained" onClick={fetchData}>
          Load More
        </Button>
      </Box>
    </div>
  );
}

export default Adspace;

And here is firestore database rules for this collection

 match /Products/{userid}{
        allow create:if request.auth.uid!=null
      allow read: if request.auth.uid!=null
      allow write:if request.auth.uid==userid
      allow delete:if request.auth.uid!=null
    }

AJAX, using onreadystatechange() but still not working

I have been working on a XML, HTTP communication , and I do not understand why my code seems to have some type of error. When sending a get request, sometimes it fails to get response or even to send to the server(I believe, as no message is shown). When I include alerts it does work. I understand this is due to asynchronous programming, as the alerts give more time to the operation. But even so, I am working with onreadystatechange() so I do not understand. Here is the code:

<script  type ="text/javascript">

const xhr = new XMLHttpRequest();
function sendData() {
const getEnter = document.getElementById('p_input').value;
const cont = document.getElementById('cont');
var url = "http://192.168.1.132:4344?";
url += getEnter;

xhr.onreadystatechange = () => {
    if(xhr.readyState==4 && xhr.status==200){
        console.log("success");

    }
}
xhr.open('GET',url,true);
cont.textContent ="processing";
xhr.send();
}
</script> 

I am calling this function on the onClicked event of a button. It would be excellent if someone knew how to fix this

return value remains undefined even when timed out for 10 seconds

I had an issue where I needed to return the response of an async function which kept being returned as undefined. So I decided to use setTimeout() before trying to use it. It still doesn’t seem to work. Can someone explain why?

My attempt:

insertUser = (req,res) => {
    var record = {
        'handle': req.body.handle,
        'name': req.body.name,
        'password': req.body.password
    };
    var response;
    createUser(record, response)
    setTimeout(() => {
        console.log(response);
    },10000)
};

createUser = (record, response) => {
    users.insertOne(record, function(err, result){
        if(err){
            response = {'code': 404, 'message': 'Something went wrong. Message: ', err} 
        }else{
            response = {'code': 200, 'message': result.insertedId}
        }
    })
    setTimeout(() => {
        console.log(response)
    }, 1000);
};

How do I create a custom Form with FormData and upload to a server as PHP

If you wanted to upload randomText - 5994 text to a PHP server without the client using a <form> and data was sent in the background, how would you do it?
I guess this should be my code…

let xhr = new XMLHttpRequest();
xhr.open("log.php","POST");
//correct after this line.
xhr.send('{"name":"Sample Form Data","age":".."}');
xhr.close();

The code should send a request + data and the PHP code will do the rest.
This is the PHP code.

$name = $_POST["name"];
$age = $_POST["age"];
echo "client: ".$name."age".$age."yrs";

Why unary operator before exponentiation expression in JavaScript cannot be evaluated? [duplicate]

I noticed that expression like “-3**2” is considered ambiguous in JavaScript. For example, in Chrome, the error is thrown as “Uncaught SyntaxError: Unary operator used immediately before exponentiation expression. Parenthesis must be used to disambiguate operator precedence.”

From the perspective of compiler (specifically, parser I think) or syntax designer, why this input is not allowed? If I were the designer of the compiler, maybe I would just assign a higher precedence to unary operator, or the other way, instead of throw an error.

how to change navigation focus view of v-date-picker with manual trigger

i made vue date range picker manually using v-list and v-date-picker :

<v-card width="600" elevation="1" rounded>
    <v-container class="pa-0" fluid>
      <v-row dense no-gutters>
        <v-col cols="3" style="height: 100%">
          <v-list>
            <v-list-item-group v-model="select">
              <v-list-item v-for="(item, i) in items" :key="i">
                <v-list-item-content>
                  <v-list-item-title v-text="item.time" @click="tes(item.duration)"></v-list-item-title>
                </v-list-item-content>
              </v-list-item>
            </v-list-item-group>
          </v-list>
        </v-col>
        <v-divider></v-divider>
        <v-col cols="9">
          <v-date-picker ref="tes" v-model="dates" range full-width>
            <template>
              <v-container class="pa-0">
                <v-row>
                  <v-col cols="6"><YBtn block secondary>Cancel</YBtn></v-col>
                  <v-col cols="6"><YBtn block>Apply</YBtn></v-col>
                </v-row>
              </v-container>
            </template>
          </v-date-picker>
        </v-col>
      </v-row>
    </v-container>
</v-card>

and my script :

export default {
data() {
    return {
    select: { time: 'Today', duration: 'today' },
    items: [
        { time: 'Today', duration: 'today' },
        { time: 'Yesterday', duration: 'yesterday' },
        { time: 'This Month', duration: 'thismonth' },
        { time: 'This Year', duration: 'year' },
        { time: 'Previous Month', duration: 'previousmonth' }
    ],
    dates: [this.$moment().format('YYYY-MM-DD')]
    }
},

methods: {
    tes(e) {
    switch (e) {
        case 'yesterday':
        this.dates = this.$moment().subtract(1, 'days').format('YYYY-MM-DD')
        break
        case 'thismonth':
        this.dates = [
            this.$moment().startOf('month').format('YYYY-MM-DD'),
            this.$moment().endOf('month').format('YYYY-MM-DD')
        ]
        console.log(this.dates)
        break
        case 'year':
        this.dates = [
            this.$moment().startOf('year').format('YYYY-MM-DD'),
            this.$moment().endOf('year').format('YYYY-MM-DD')
        ]
        console.log(this.dates)
        break
        case 'previousmonth':
        this.dates = []
        this.dates = [
            this.$moment().startOf('month').subtract(1, 'months').format('YYYY-MM-DD'),
            this.$moment().endOf('month').subtract(1, 'months').format('YYYY-MM-DD')
        ]
        console.log(this.dates)
        break
        default:
        this.dates = this.$moment().format('YYYY-MM-DD')
        break
    }
    }
}
}

when i click on previous month, it succesfully change v-date-picker value to the selected previous month. but, the navigation still in current month. how do i change v-date-picker navigation focus to selected previous month?

as you can see there, the focus navigation at december. what i want when i click prevous month. it showing november, which is the previous selected month

Native Javascript click event not working on icon in button

I have a button in my HTML + Tailwindcss page like so:

<div class="fixed bottom-4 right-4 z-10">

    <button
        id="button-fab-anchor"
        class="z-50 whitespace-nowrap flex items-center px-3.5 py-2 rounded-full shadow-xl
           outline-none focus:outline-none border-t border-b border-transparent
           combo-primary hover:bg-primary-contrast active:bg-primary-contrast"
    >
        <span class="z-40 icon-inverse-primary text-lg text-center">
            <i id="up-icon" class="fal fa-chevron-up"></i>
            <i id="down-icon" class="fal fa-chevron-down hidden"></i>
        </span>

    </button>

    <ul id="button-fab-list" class="absolute bottom-full right-0 flex flex-col justify-end hidden">
        <li> Buttons here... </li>
    </ul>

</div>

On the page I have the following JS:

document.addEventListener("DOMContentLoaded", function(event) {

    const btnAnchor = document.getElementById('button-fab-anchor');

    if (btnAnchor) {

        const btnList = document.getElementById("button-fab-list");
        const upIcon = document.getElementById("up-icon");
        const downIcon = document.getElementById("down-icon");

        btnAnchor.addEventListener("click",  function(event) {
            if (event.target == btnAnchor) {
                btnList.classList.toggle('hidden');
                upIcon.classList.toggle('hidden');
                downIcon.classList.toggle('hidden');
            }
        });

    }

});

This works fine if I click on the button but not on the icon in the button. I have tried using z-index to place the button parent at z-50 and the icon as z-10 so the parent is stacked above the child.

What sis I miss / How do I set up the event to work on the button parent and all its children (i.e.: the icon)?

How do I access a constructor “this” variable? [duplicate]

In my updateCamera(event) function, I am trying to access this.camera as can be shown in my constructor. Unfortunately, it’s undefined in that function, I assume it’s a scope issue, but I’m not sure how to solve it. Any ideas? Thank you.

export default class Experience {
    constructor(options = {}) {
        this.camera = new Camera();
        // removed unnecessary stuff
        this.onMouseDrag();
    }

    updateCamera(event) {
        console.log(this.camera); //Prints "undefined" in the console
        this.camera.position.x = (event.clientX / window.innerWidth) * 2 - 1;
    }

    onMouseDrag() {
        window.addEventListener("mousedown", () => {
            window.addEventListener("mousemove", this.updateCamera);
        });
        window.addEventListener("mouseup", () => {
            window.removeEventListener("mousemove", this.updateCamera);
        });
    }

Javascript single quote inside string for exported text file [duplicate]

I am creating a node.js file that creates and readme file where the install directions need to be displayed as shell or javascript type font. However, I have not been able to use the single quotes required to make that work since they close out the string.

function generateExport(data) {
  const { username, ...title} = data;

  return `
    ```shell <--- how would you do this ?
    ${data.title} 
    ```  <----- and this?
`;
}