Reverting to a “default” jquery function after mouseout

I’m making some boxes move around randomly when the cursor is not over the div that contains them. They will only follow the mouse when it is “hovering” over div.
However I am trying to make the boxes revert to their random “default” movement after the mouseout. If the user scrolls over the div, then the images follow again. I know the function I am trying to use looks like this but somehow I can’t seem to make it work.

<script>
$(document).ready(function(){
  $("(boxes ref)").mouseover(function(){
    (follow cursor)
  });
  $("(boxes ref)").mouseout(function(){
    (random movement)
  });
});
</script>

Original code:

<!DOCTYPE html>
<html>
<head>
<style>

div#container {height:500px;width:500px;}

.a {

position:fixed;
    
}
.b {

position:fixed;
    
}
.c {

position:fixed;
    
}

</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>

$(document).ready(function() {
    animateDiv($('.a'));
        animateDiv($('.b'));
        animateDiv($('.c'));

});

function makeNewPosition($container) {

    // Get viewport dimensions (remove the dimension of the div)
    var h = $container.height() - 50;
    var w = $container.width() - 50;

    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);

    return [nh, nw];

}

function animateDiv($target) {
    var newq = makeNewPosition($target.parent());
    var oldq = $target.offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);

    $target.animate({
        top: newq[0],
        left: newq[1]
    }, speed, function() {
        animateDiv($target);
    });

};

function calcSpeed(prev, next) {

    var x = Math.abs(prev[1] - next[1]);
    var y = Math.abs(prev[0] - next[0]);

    var greatest = x > y ? x : y;

    var speedModifier = 0.03;

    var speed = Math.ceil(greatest / speedModifier);

    return speed;

}

</script>
</head>
<body>

<div id="container">
 <img src="https://preview.redd.it/u89vxytsqax41.png?auto=webp&s=fe77dd09acb7fd89a637da1b2da760cc9862dc07" alt="prgm" class='a' id='image'>
  <img src="https://preview.redd.it/u89vxytsqax41.png?auto=webp&s=fe77dd09acb7fd89a637da1b2da760cc9862dc07" alt="prgm" class='b' id='image2'>
 <img src="https://preview.redd.it/u89vxytsqax41.png?auto=webp&s=fe77dd09acb7fd89a637da1b2da760cc9862dc07" alt="prgm" class='c' id='image3'>
</div>

<script>

$(document).mousemove(function(e){
/*duration determines the speed of the animation (in this case, the speed to which prgm follows)*/
    $("#image").stop().animate({left:e.pageX, top:e.pageY}, {duration: 5000});
});

</script>

<!-- make the images follow the cursor -->
<script>

$(document).mousemove(function(e){
/*duration determines the speed of the animation (in this case, the speed to which prgm follows)*/
    $("#image2").stop().animate({left:e.pageX, top:e.pageY}, {duration: 5000});
});

</script>

<script>

$(document).mousemove(function(e){
/*duration determines the speed of the animation (in this case, the speed to which prgm follows)*/
    $("#image3").stop().animate({left:e.pageX, top:e.pageY}, {duration: 5000});
});

</script>

</body>
</html>

Thanks

Mongoose not saving document, getting “MongoClient must be connected” error

I am trying to connect to MongoDb using mongoose. Here is the code I am using to connect:

controller.js

const conn = mongoose.createConnection(db, {
            useNewUrlParser: true,
            useUnifiedTopology: true
        })

        conn.once('open', () => {
            console.log(`${req.body.db} DB connected`)
            const model = conn.model(`item`, Item, req.body.collection)

            let stuff = uploadToS3(req.files)
            stuff.then(paths => {
                const newItem = new model({
                    nameOfItem: req.body.name,
                    pictures: paths,
                    description: req.body.description,
                    year: req.body.year,
                    favorite: req.body.favorite
                })

                //save data to MongoDB
                newItem.save()
                    .then(item => {
                        console.log(item)
                        res.json(item)
                    })
                    .catch(err => console.log(err))
                conn.close()
            })
        })

I don’t think this matters, but I will state it anyway. I am using a single schema for several different databases and collections. Here is the schema:

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const pictureSchema = new Schema({
    name: String,
    path: String
})
const itemSchema = new Schema({
    nameOfItem: { type: String, required: true },
    pictures: [pictureSchema],
    description: String,
    year: String,
    favorite: {type: Boolean, default: false}
})

module.exports = itemSchema

And I am pulling the schema into the controller using this:

const Item = require('../models/item.model')

Here is the output:

bottles DB connected
{
  fieldname: 'photos',
  originalname: 'DSCN5104.JPG',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  destination: 'uploads/',
  filename: '1c17e793b340658f14bcc92c98444d95',
  path: 'uploads\1c17e793b340658f14bcc92c98444d95',
  size: 2107729
}

MongoNotConnectedError: MongoClient must be connected to perform this operation
    at getTopology (C:UsersuserOneDriveDesktopProjectservernode_modulesmongodblibutils.js:367:11)
    at Collection.insertOne (C:UsersuserOneDriveDesktopProjectservernode_modulesmongodblibcollection.js:150:82)
    at NativeCollection.<computed> [as insertOne] (C:UsersuserOneDriveDesktopProjectservernode_modulesmongooselibdriversnode-mongodb-nativecollection.js:200:33)
    at model.Model.$__handleSave (C:UsersuserOneDriveDesktop\Projectservernode_modulesmongooselibmodel.js:294:33)
    at model.Model.$__save (C:UsersuserOneDriveDesktopProjectservernode_modulesmongooselibmodel.js:374:8)
    at C:UsersuserOneDriveDesktopProjectservernode_moduleskareemindex.js:281:16
    at C:UsersuserOneDriveDesktopProjectservernode_moduleskareemindex.js:78:15
    at processTicksAndRejections (internal/process/task_queues.js:79:11)
bottles DB closed

What confuses me is that it says that it is connected and giving me that error at the same time. Any help is appreciated.

nodemon ERROR app crashed – waiting for file changes before starting

I’m on the project logging page using JWT in node js. But today, when I was running the “nodemon index or nodemon index.js” command on vscode terminal, I got a message like this.

PS E:OneDriveDocumentsJWT AUTHjsonwebt> nodemon index          
[nodemon] 2.0.15
[nodemon] to restart at any time, enter `rs`                        
[nodemon] watching path(s): *.*                                                     
[nodemon] watching extensions: js,mjs,json                        
[nodemon] starting `node index index.js`    
internal/process/esm_loader.js:74
    internalBinding('errors').triggerUncaughtException(
                              ^                                    

Error [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import 'E:OneDriveDocumentsJWT AUTHjsonwebtnode_modulessequelizedist' is not supp orted resolving ES modules imported from E:OneDriveDocumentsJWT AUTHjsonwebtcontrollersusers.js
    at finalizeResolution (internal/modules/esm/resolve.js:272:17) 
    at moduleResolve (internal/modules/esm/resolve.js:699:10)      
    at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:810:11)
    at Loader.resolve (internal/modules/esm/loader.js:86:40)       
    at Loader.getModuleJob (internal/modules/esm/loader.js:230:28) 
    at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:56:40)
    at link (internal/modules/esm/module_job.js:55:36) {
  code: 'ERR_UNSUPPORTED_DIR_IMPORT',
  url: 'file:///E:/OneDrive/Documents/JWT%20AUTH/jsonwebt/node_modules/sequelize/dist'
}

[nodemon] app crashed - waiting for file changes before starting...

This just happened, because yesterday when I used the command, it was all right.
And this is the result when I run “dir”.

PS E:OneDriveDocumentsJWT AUTH> dir

    PS E:OneDriveDocumentsJWT AUTHjsonwebt> dir
    
        Directory: E:OneDriveDocumentsJWT AUTHjsonwebt
    
    
    Mode                LastWriteTime         Length Name
    ----                -------------         ------ ----
    da---l        1/11/2022   2:42 PM                config
    da---l        1/11/2022   3:31 PM                controllers
    da---l        1/11/2022   3:01 PM                models
    da---l        1/11/2022   2:35 PM                node_modules
    da---l        1/11/2022   3:35 PM                routes
    -a---l        1/11/2022   5:04 PM            115 .env
    -a---l        1/13/2022   9:01 AM            448 index.js
    -a---l        1/11/2022   2:33 PM          44993 package-lock.json       
    -a---l        1/13/2022   8:44 AM            515 package.json
    -a---l        1/13/2022   8:48 AM            226 request.rest

Is there any advice that can help me? TIA^^

here’s my package.json

{
  "name": "jsonwebt",
  "version": "1.0.0",
  "description": "json web token login",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "start": "nodemon index.js",
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "rara",
  "license": "ISC",
  "dependencies": {
    "bcrypt": "^5.0.1",
    "cookie-parser": "^1.4.6",
    "cors": "^2.8.5",
    "dotenv": "^11.0.0",
    "express": "^4.17.2",
    "jsonwebtoken": "^8.5.1",
    "mysql2": "^2.3.3",
    "sequelize": "^6.13.0"
  }
}

here’s my index.js

import express from "express";
import dotenv from "dotenv"
import db from "./config/database.js";
import router from "./routes/index.js";
dotenv.config();
const app = express();

try {
    await db.authenticate();
    console.log('CONGRATULATIONS!! Database Connected...');
} catch (error) {
    console.error(error);
}

app.use(express.json());
app.use(router);

app.listen(5000, () => console.log('Server Running at Port 5000'));

Javascript uncaught type error is not a function Builder Pattern

I am building a validator using a Builder Pattern. Not sure if I am using the correct pattern but I keep on having Javascript uncaught type error is not a function although my codes works.

Full Error msg:

Uncaught TypeError: validate.IsTCAgree(...).IsRMGTCAgree is not a function 
at HTMLButtonElement.<anonymous> (TPR:1846:115) 
at HTMLButtonElement.dispatch (jquery-3.5.1.js:5429:27) 
at HTMLButtonElement.elemData.handle (jquery-3.5.1.js:5233:28)
$btnSubmit.click(function(e) {
      var validate = new ValidatorTnCBuilder($btnSubmitErrMsg);
      if (validate.IsTCAgree('Please check Terms and Conditions.').IsRMGTCAgree('Please check 
          agreement.
          ')) {
          // do sth
        }
      });
    const ValidatorTnCBuilder = function($el) {
      return {
        IsTCAgree: function(msg) {
          if (!$checkIsTCAgree.is(':checked')) {
            $el.text(msg);
            return false;
          }
          return this;
        },
        IsRMGTCAgree: function(msg) {
          if (!$checkIsRMGTCAgree.is(':checked')) {
            $el.text(msg);
            return false;
          }
          return this;
        }
      }
    }

change string in multidimensional array to object depending on index prop of object within another array [duplicate]

I have two arrays. my Array1 is a multi-dimensional array of just strings.

The Array2 is an array of objects. each object has 2 key value pairs one is called “value” the other is “HeaderIndex”

If Array1 has an array with a string a index 0 I want to find the “value” key from Array2 and convert the Array1 string to a new object matching the HeaderIndex value.

I am trying to convert the multi dimensional array to another multidimensional array but instead of strings, I want it to be objects depending on index prop from Array2

const Array1 = [ 
['Alex', 'Boe', 'MeowWolf', 'pizza', 'pink'],
['Arron', 'Coe', 'Kmart', 'tofu', 'purple'],
['Jane', 'Doe', 'Sears', 'tacos', 'orange'],
['John', 'Eoe', 'YugiOh', 'blueberries', 'magenta'],
['Suzie', 'Boe', 'Toyota', 'steroids', 'blue']
]


const Array2 = [
    { value: 'First name', HeaderIndex: 0},
    { value: 'Last name', HeaderIndex: 1},
    { value: 'Company', HeaderIndex: 2},
    { value: 'Favorite food', HeaderIndex: 3},
    { value: 'Favorite color', HeaderIndex: 4},
]

I am trying to get this output below

const Finalresult = [ 
[{First name: 'Alex'}, {Last name: 'Boe'}, {company: 'MeowWolf', {Favorite food: "pizza", {Favorite color: "pink"}],

[{First name: 'Arron'}, {Last name: 'Boe'}, {company: 'Kmart', {Favorite food: "tofu", {Favorite color: "purple"}],

[{First name: 'Jane'}, {Last name: 'Doe'}, {company: 'Sears', {Favorite food: "tacos", {Favorite color: "orange"}],

[{First name: 'John'}, {Last name: 'Eoe'}, {company: 'YugiOh', {Favorite food: "blueberries", {Favorite color: "magenta"}],

]

Axios 404 error finding /api/private when not authenticating at root director

I was following a tutorial to create a user authentication – a user dashboard page is hidden and appears if the user is logged in. It works perfectly fine at the / directory but not if I change the / directory to /dashboard, even if I update all instances of "/" to "/dashboard".

Here’s my Axios code for authenticating if the user is logged in; the problem arises in /api/private, where I get a 404 error GET http://localhost:3000/api/private 404 (Not Found) ONLY when the directory for the user’s dashboard is NOT at "/".

  const fetchPrivateDate = async () => {
      const config = {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${localStorage.getItem("authToken")}`,
        },
      };

      try {
        const { data } = await axios.get("/api/private", config);
        setPrivateData(data.data);
      } catch (error) {
        localStorage.removeItem("authToken");
        console.log(error);
        setError("Error");
      }
    };

    fetchPrivateDate();
  }, []);

Here is the server node.js code:

app.get("/dashboard", (req, res, next) => {
  res.send("Operational");
});

app.use("/api/auth", require("./routes/auth"));
app.use("/api/private", require("./routes/private"));

I believe the /auth path works; login and signup work completely fine, it’s just that once the user logs in the dashboard it catches an error because it can’t find api/private.

Here is routes/private aka api/private:

const express = require("express");
const router = express.Router();
const { getPrivateRoute } = require("../controllers/private");
const { protect } = require("../middleware/auth");

router.route("/dashboard").get(protect, getPrivateRoute);

module.exports = router;

I looked at plenty of other posts, such as this one: Method Post with Axios giving Error 404. ReactJS but none of the changes, such as updating the axios.get to include localhost:3000 works at all. For reference, this is the tutorial I followed: https://www.youtube.com/watch?v=YocRq-KesCM&list=LL. I’ve tried several solutions online and nothing seems to work. Any help would be greatly appreciated.

Image Tag In HTML not clicking with jQuery

I’m making a clicker game but one of my images (for an upgrade) won’t work when I click it. The problem is in the helper div image.
I’m using HTML , css, javascript and jQuery for js

Code:

var clicks = 0;
var perclick = 1;
var persec = 0;
var costup1 = 12;
var currentup1 = 0;
var costup2 = 27;
var currentup2 = 0;
setInterval(sec, 1000)
//click and upgrade
$(document).ready(function() {
  $("#sun").click(function() {
    add()
  })
  $("#up1").click(function() {
    if (clicks >= costup1) {
      clicks = clicks - costup1
      currentup1 = currentup1 + 1;
      costup1 = ((currentup1 + 1) * 12);
      perclick = perclick + 1
      update()
    } else {
      alert("You Don't Have Enough Clicks");
    }
  })
  $("#up2").click(function() {
    if (click >= currentup2) {
      clicks = clicks - costup2
      currentup2 = currentup2 + 1;
      costup2 = ((currentup2 + 1) * 27)
      persec = persec + 1;
      update()
    } else {
      alert("You Don't Have Enough Clicks")
    }
  })
  //Save and load
  $(document).ready(function() {
    $("#save").click(function() {
      localStorage.setItem("clicks", clicks)
      localStorage.setItem("perclick", perclick)
      localStorage.setItem("persec", persec)
      localStorage.setItem("currentup1", currentup1)
    })
    $("#load").click(function() {
      clicks = localStorage.getItem("clicks")
      clicks = parseInt(clicks)
      perclick = localStorage.getItem("perclick")
      perclick = parseInt(perclick)
      persec = localStorage.getItem("persec")
      persec = parseInt(persec)
      currentup1 = localStorage.getItem("currentup1")
      currentup1 = parseInt(currentup1)

    })
  })
})


function add() {
  clicks = clicks + perclick;
  update()
}

function sec() {
  clicks = clicks + persec;
  update()
}

function update() {

  document.getElementById("costmag").innerHTML = ((currentup1 + 1) * 12) + " Clicks";
  document.getElementById("curmag").innerHTML = "You Own " + currentup1 + " Magnifying Glasses(+1 Clicks Per Click)"
  document.getElementById("scoreText").innerHTML = clicks + " Clicks";
  document.getElementById("clickText").innerHTML = "You Are Gaining " + perclick + " Clicks Per Click"
  document.getElementById("secText").innerHTML = "You Are Gaining " + persec + " Clicks Per Second"

  document.getElementById("helpcur").innerHTML = "You Have " + currentup2 + " Helpers(+1 Clicks Per Second)"
  document.getElementById("helpcos").innerHTML = ((currentup2 + 1) * 27) + " Clicks";

}
img {
  -webkit-user-drag: none;
}

button {
  box-sizing: border-box;
  background-color: #000000;
  color: cyan;
  border: none;
  font-size: 16px;
}

body {
  font-family: Architects Daughter;
}

```
<!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">
  <title>Clicker Game Made With jQuery</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="script.js"></script>
  <link rel="stylesheet" href="styles.css">
</head>

<body>

  <p id="clickText"> You Are Gaining 1 Clicks Per Click </p>
  <p id="secText"> You Are Gaining 0 Clicks Per Second </p>
  <a href="javascript:;"><img src="Images/sun.png" id="sun"></a>
  <p id="scoreText">0 Clicks</p>


  <div class="magnify">
    <p id="curmag"> You Own 0 Magnifying Glasses(+1 Clicks Per Click)</p>
    <a href="javascript:;"><img src="Images/magnify-glass.png" width="50px" height="50px" id="up1"></a>
    <p id="costmag"> 12 Clicks </p>
  </div>



  <div class="helper">
    <p id="helpcur"> You Have 0 Helpers (+1 Clicks Per Second)</p>
    <a href="javascript:;"><img src="Images/helper.png" width="60px" height="80px" id="up2"></a>
    <p id="helpcos"> 27 Clicks </p>
  </div>

  <div class="svld">
    <button id="save">Save</button>
    <button id="load">Load</button>
  </div>

</body>

</html>

vjs video is not showing in Chrome and Firefox, but working in Safari

I am using a fullpage js and the site is
https://ldmm2-harmonie.netlify.app/

Here is my code for the video

  <link href="https://vjs.zencdn.net/7.17.0/video-js.css" rel="stylesheet" />
  <script src="https://vjs.zencdn.net/7.17.0/video.min.js"></script>
  <link href="https://unpkg.com/@videojs/[email protected]/dist/sea/index.css" rel="stylesheet"/>
  <script src="js/jquery-3.1.1.min.js"></script>
        <div class="container">
           <div id="videoSectionCarousel" class="carousel slide" data-interval="false">
              <video id="example_video_1"  class="video-js vjs-fluid vjs-nofull vjs-theme-sea" controls preload="auto" width="800" height="521" playsinline="playsinline" poster="img/video_poster_523.jpg" data-setup="{}">
                 <!-- poster="img/dummy-video-img.jpeg" -->
                 <source src="https://ldmm2-harmonie.netlify.app/img/videoSection/sales-video.mp4" type="video/mp4">
                 <source src="http://vjs.zencdn.net/v/oceans.ogv" type="video/ogg">
                 <p class="vjs-no-js">To view this video please enable JavaScript, and consider upgrading to a web browser that <a href="https://videojs.com/html5-video-support/" target="_blank">supports HTML5 video</a></p>
              </video>
           </div>
        </div>

For some reason it is not showing anymore. It works in Safari….

Is there a way I can manually update client side contents after sign-up

I’m a front end dev on my way to backend and this is a personal project. It was meant to be static so all users see the same information on their page but now I want to be able to change some details based on the clients who signs up. For example. All users were meant to see a $20 bill for a community project but now I want to be able to increase or decrease that amount on different client user page.

How to run C code in a website privately? [closed]

I have written really complex (about 2000 lines of code) and useful C program, and I want to run it in my website. I know that there are some services where you can paste your code and let everyone compile it and see it.
But I want to make it in way that visitors can only run the code, and they cannot see it.
Also, I want to update if needed.
Could you tell me if you know anything that would help me in this?

Issue related to event propagation

I’m having an issue with event propagation in JavaScript. I have different data and single form attached to each child element. To prevent an event from propagating to each child element and it’s parent I am using stopImmediatePropagation(). The other method like following doesn’t work.

event.cancelBubble = true;
//OR
event.stopPropagation();
//OR
yourFormSubmissionElement.removeEventListener('submit', submitCreatePlistForm, false);
yourFormSubmissionElement.addEventListener('submit', submitCreatePlistForm, false)

Problem that I’m having is that the data that was linked to each individual element become same in each call, i.e. if the form submission was to send DATA01, DATA02, DATA03 etc. for element1, element2, element3… respectively, then on each submission DATA01 is sent back to backend when I use stopImmediatePropagation() in this.

//Each Button in the playlist has this event listener with their own data passed as argument
const listenFormSubmission = async (data) => {
    const taskAForm = document.querySelector('<selector>');

    const submitTaskAForm = async function(e) {
        e.preventDefault();
        // e.cancelBubble = true;
        // e.stopPropagation();
        e.stopImmediatePropagation();

        await axios.post('/target', data).then(async function(errResponse){
            console.log(errResponse)});
        }
        taskAForm.addEventListener('submit', submitTaskAForm, false);
    }

If anyone can give suggestions on how to handle this, that will be of great help.
And though I already have gone through most of the related articles and questions any other useful reference in your knowledge will be greatly appreciated.

sending data in forms html to mysql data base using Node.Js

Hello I am doing an exercise that the main goal is to create a RestAPI with Node.js and test it in small hmtl application. My teacher helped us create the RestAPI with an example, and I was able to adapt it to my own mysql database, and tested every endpoint of the API using Thunder Client extension on Visual Studio Code, and it his working properly. However i am having problems in the testing in the html app. I am trying to send some data using a form, but as i submit, i know the endpoint it is right, because it truly connects to the right function and table, and insert new data to the table, however it doesn’t save any of the data i put in the form, instead, it inserts null values to all columns.

Here is my html form

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
   
    <title>Header</title>

    <link rel="stylesheet" href="css/styles.css">
    </head>
<body>

    <h1 id="teste"> Adicionar um Videojogo</h1>
    <form action=" http://localhost:3000/api/videogames" method="post" enctype="multipart/form-data"  >

        <div class="form-item col" id="form_">
                    <input type="text" name= "nome" id="nome" placeholder="Nome" required= "required">
                    </div>
        <div class="form-item" id="form_">
                    <input type="text" name= "produtora" id="produtora" placeholder="Produtora" required= "required">               
                    </div>
        <div class="form-item" id="form_">
                   <input type="text" name= "distribuidora" id="distribuidora" placeholder="Distribuidora" required= "required">
                    </div>
        <div class="form-item" id="form_">
                   <input type="text" name= "ano" id="ano" placeholder="Ano" required= "required">
    
                   </div>

Here is my model

const sql = require("./db.js");

// construtor
const Videogame = function(videogame) {
  this.nome = videogame.nome;
  this.produtora = videogame.produtora;
  this.distribuidora = videogame.distribuidora;
  this.ano = videogame.ano;
  this.id_genero= videogame.id_genero;
  this.id_plataforma = videogame.id_plataforma;
}

Videogame.insert = (newVideogame, result) => {
  sql.query('INSERT INTO videogame SET ?', newVideogame, (err, res) => {
    if (err) {
      console.log('error: ', err);
      result(err, null);
      return;
    }

    console.log("Videojogo inserido: ", { id: res.insertId, ...newVideogame });
    result(null, { id: res.insertId, ...newVideogame});
  });
}

My Controller

const Videogame = require("../models/videogame.model.js");

// Inserir um novo videojogo
exports.insert = (req, res) => {
    // Validar a request
    if (!req.body) {
      res.status(400).send({
        message: "O conteúdo do videojogo deve estar definido."
      });
    }
  
    // Criar um "Videogame"
    const videogame = new Videogame({
      nome: req.body.nome,
      produtora: req.body.produtora,
      distribuidora: req.body.distribuidora,
      ano: req.body.ano,
      id_genero: req.body.id_genero,
      id_plataforma: req.body.id_plataforma,
    });
  
    // Guardar "Videogame" na base de dados
    Videogame.insert(videogame, (err, data) => {
      if (err)
        res.status(500).send({
          message:
            err.message || "Ocorreu um erro ao inserir o videojogo..."
        });
      else res.send(data);
           
    });
  };

My routes

module.exports = app => {
    const videogames = require("../controllers/videogame.controller.js");
  
    var router = require("express").Router();
  
    // Consultar todos os videojogos
    router.get("/", videogames.selectAll);
  
    // Consultar um videojogos pelo id
    router.get("/:id", videogames.findById);
  
    // Inserir um novo videojogo
    router.post("/", videogames.insert);
  
    // Atualizar um videojogo pelo id
    router.put("/:id", videogames.update);
  
    // Apagar um videojogo pelo id
    router.delete("/:id", videogames.delete);
  
    // Apagar todos os videojogos
    router.delete("/", videogames.deleteAll);
  
    app.use('/api/videogames', router);
  };

Here is the result that appear on the terminal, after i submit my form

Videojogo inserido:  {
  id: 14,
  nome: undefined,
  produtora: undefined,
  distribuidora: undefined,
  ano: undefined,
  id_genero: undefined,
  id_plataforma: undefined
}

It should save the data i use in forms instead of undefined ( i also have 2 radio buttons for id_genero and id_plataforma on my forms, but i only put the others here, because i don’t think the problem is not with the radio buttons, as if it were, it would at assign the other values in forms.

Thanks in advance

Is there a way to get the element that is visually underneath or above or left or right a certain element?

I am working on simple game (classic number game) with JavaScript
in which a container div with display Flex contains 9 divs
8 divs are blue with numbers inside from 1 to 8 and 1 div is white without any content
each time the page loaded the divs are ordered randomly
image of the game

and the empty div is placed randomly too.

the mission is to rearrange the numbers from 1 to 8 that when you click on any div that is visually neighbor (above, beneath, left or right)

to the empty div
they are switch their positions
in this image the divs that are allowed to move are 4,7,5
How I can make it with javaScript or jquery ?

here is my code:

$(document).ready(function(){
  var arr = [];
  
  for(i=1;i<9;i++)
  {
    arr.push(i);
  }
  
  arr.push("");

  function shuffleArray(array) 
  {
    for (let i = array.length - 1; i > 0; i--) 
    {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
    }
  }
  
  shuffleArray(arr);

  for(i=0;i<9;i++)
  {
    divContent.innerHTML += "<div class='tile'>"+arr[i]+"</div>"
  }

  var tile = document.getElementsByClassName("tile");

  var n = 0;

  while (n < tile.length) 
  {
    if (tile[n].textContent != (n+1))
      break;
    
    tile[n].style.color = "yellow";
    n++;
  }

  for(i=0;i<tile.length;i++)
  {
    if(!tile[i].textContent)
    {
      tile[i].style.backgroundColor  = "#fff";
      tile[i].classList.add("whitt");
    }
    tile[i].style.color = "#fff";
  }

  $('.tile').click(function (evt) {
    var $div = $(evt.target).closest('.tile');
    $div.next('.tile').after($div).animate({opacity: 0.9, top:'100'}, 500 );

    for(i=0;i<tile.length;i++)
    {
      if(!tile[i].textContent)
      {
        tile[i].style.backgroundColor  = "#fff";
        tile[i].classList.add("whitt");
      }
      tile[i].style.color = "#fff";
    }

    n = 0;
    
    while (n < tile.length) 
    {
      tile[n].style.color = "#fff";
      if (tile[n].textContent != (n+1)) 
        break;
      tile[n].style.color = "yellow";
      n++;
    }
  });
});
.flexDiv{
  display:flex;
  flex-wrap: wrap;
  width:310px;
  border:1px solid black;
}
.tile{
  position:relative;
  background:#08088A;
  text-align:center;
  width:29%;
  margin:1px;
  font-size:75px;
  font-weight:bold;
  color:#fff;
  padding:5px;
}
.wh{
  background:#fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<div id="divContent" class="flexDiv"></div>

How to redirect page using targetURL with my datepicker

I am tweaking with Twisty’s script – Using Jquery UI Datepicker to redirect to URL: Change URL value based on the selected date

I am trying let user click on a date which will be redirect to a page according to the date selected. But I am getting this alert – Redirect to undefined, no matter how I tweaked the script.
Hence, I would appreciate your help. Thank you.

Pick a date:

<script>
$(function() {
  function getDayOfYear(n) {
    var s = new Date(n.getFullYear(), 0, 0);
    var d = (n - s) + ((s.getTimezoneOffset() - n.getTimezoneOffset()) * 60 * 1000);
    var oneDay = 1000 * 60 * 60 * 24;
    var day = "00" + Math.floor(d / oneDay);
    return day.substr(-3);
  }

  var targetUrl;

  $("#datepicker")
    .datepicker({
      dateFormat: 'dd-mm-yy',
      onSelect: function(dateText) {
      datePicked = $.datepicker.parseDate('dd-mm-yy', dateText);
       dayPicked = getDayOfYear(datePicked);
       targetUrl  =  "https://datepicker.com/" + dayPicked;
        $(this).change();
      }
    })
    .change(function() {
      alert("Redirect to " + targetUrl);
      //window.location.href = targetUrl;
    });
});
</script>