I am opening a link (Link is Google Drive link) in using jquery script but that link Redirects to app when target is “_blank” and not in BrowserNewTab

I am creating Drive Direct link generator tool for that I have encountered this problem. When The direct link is generated a notification pops in which direct link is embedded that direct link is not opening in new tab and redirecting
to google drive app

Plz anyone give problem to this.

Tool: Google Drive Direct Link Generator Tool

Code: Click here

Direct Link From my Tool: Click here

I’m Having a TypeError on NodeJS for POST method on MongoDB: Cannot read properties of undefined (reading ‘name’)

I know this question has been asked a lot of times but the majority of them is for frameworks or other tech stacks, I’m using NodeJS with Express and a database on MongoDB and I’m testing my API with Postman. When I try to send the request to the API on POST return the next message (ON the app, Postman just sends: Could not get response):

addProductsCart.js:21
_req$body = req.body, name = _req$body.name, description = _req$body.description, image = _req$body.image, price = _req$body.price, productType = _req$body.productType;
^
TypeError: Cannot read properties of undefined (reading ‘name’)

going to the file that the error sends it seems like there’s nothing wrong

import Product from '../models/Products';
import Cart from '../models/Cart';


const addProductCart = async (req, res) => {

    const {name, description, image, price, productType} = req.body;
    

    const estaEnProducts = await Product.findOne({name});
  

    const noEstaVacio = name !== "" && description !== "" && image !== "" && price !== "" && productType !== "";
  

    const estaEnElCarrito = await Cart.findOne({name});
  

    if (!estaEnProducts) {
      res.status(400).json({
        mensaje: "This products is not in our DataBase",
      });
  
    } else if (noEstaVacio && !estaEnElCarrito) {
      const newProductInCart = new Cart({name, description, image, price, productType, amount: 1 });
  
      /* Update the property of inCart */
      await Product.findByIdAndUpdate(
        estaEnProducts?._id,
        { inCart: true, name, description, image, price, productType },
        { new: true }
      )
        .then((product) => {
          newProductInCart.save();
          res.json({
            mensaje: `Product added correctly`,
            product,
          });
        })
        .catch((error) => console.error(error));
  
      /* Validate if product is already in cart */
    } else if (estaEnElCarrito) {
      res.status(400).json({
        mensaje: "Product already in cart",
      });
    }
  };
  
  module.exports = addProductCart;

in my models i’m using the exact same names for the controllers:

import {Schema, model} from 'mongoose';

const cartSchema = new Schema({
    name: {type: String, required: true, unique: true},
    description: {type: String, required: true},
    image: {type: String, required: true, unique: true},
    price: {type: Number, required: true},
    productType: {type: String, required: false},
    amount: {type: Number, required: true},
});

export default model('Cart',cartSchema);

and this is the product model:

import {Schema, model} from 'mongoose';

const productsSchema = new Schema({
    name: {type: String, required: true, unique: true},
    description: {type: String, required: true},
    image: {type: String, required: true, unique: true},
    inCart: {type: Boolean, default: false},
    price: {type: Number, required: true},
    productType: {type: String, required: false},
});

export default model('Products',productsSchema);

I’m using Import instead of require with Babel so there’s no problem there

I’m not able to found the error there, also I think I’m doing the petition correclty on Postman (Using the next JSON, that is a product created before on DB and telling Postman on headers that the Content-type is application/json)

{
    "name": "producto-test",
    "description": "descripcion de prueba",
    "image": "https://cdn.betterttv.net/emote/58ae8407ff7b7276f8e594f2/3x",
    "price": 100000,
    "productType": "Camara"
}

If someone knows what I’m doing wrong I’ll really apreciate that, finally I let all the log of the error, if may be helpful

TypeError: Cannot read properties of undefined (reading 'name')
    at _callee$ (C:AltoVoltajeFilmssrccontrollers/addProductsCart.js:7:12)
    at tryCatch (C:AltoVoltajeFilmsnode_modulesregenerator-runtimeruntime.js:63:40)
    at Generator.invoke [as _invoke] (C:AltoVoltajeFilmsnode_modulesregenerator-runtimeruntime.js:294:22)
    at Generator.next (C:AltoVoltajeFilmsnode_modulesregenerator-runtimeruntime.js:119:21)
    at asyncGeneratorStep (C:AltoVoltajeFilmssrccontrollersaddProductsCart.js:9:103)
    at _next (C:AltoVoltajeFilmssrccontrollersaddProductsCart.js:11:194)
    at C:AltoVoltajeFilmssrccontrollersaddProductsCart.js:11:364
    at new Promise (<anonymous>)
    at C:AltoVoltajeFilmssrccontrollersaddProductsCart.js:11:97
    at addProductCart (C:AltoVoltajeFilmssrccontrollers/addProductsCart.js:5:21)

TypeError: elem[prop] is not a function in Webdriveio

TypeError: elem[prop] is not a function

I’m facing this error in E2E testing in webdriveio. I want to click a button inside an iframe but after all, I got this error. Any help with that?

let iframe = browser.$('#fullmessage')
        browser.pause(1000)
        browser.switchToFrame(iframe)
        browser.setTimeout({ implicit: 10000 })
        let clickAgree = $('a[class="button is-success"]')
        clickAgree.click()
        browser.switchToParentFrame()
        browser.pause(3000)

Map Marker don’t show up (Marker rendered before Map)- ReactJS with @react-google-maps/api

What I want:

Having a Default ReactJS App with a Google Map

Problem:

Marker don’t display

Possible reason:

Marker been added before map finish load.

Files:

App.js, (Default ReactJS file)

Map.js, (Customized ReactJS Component)

./style/map.css

Map.js:

import { GoogleMap, useLoadScript, Marker } from "@react-google-maps/api";

import React from "react";
import "./style/map.css";

const Map = ({ zoomLevel, map_lat, map_lng, mark_lat, mark_lng }) => {
  const center = { lat: map_lat, lng: map_lng };

  const { isLoaded } = useLoadScript({
    googleMapsApiKey: "---USE API KEY HERE---",
  });

  //Return maps
  if (!isLoaded) {
    return <div>Loading...</div>;
  } else {
    return (
      <GoogleMap
        mapContainerClassName="map-container"
        zoom={zoomLevel}
        center={center}
        onLoad={() => {
          console.log("Map is loaded!");
        }}
      >
        {/* Debug Purpose */}
        {console.warn("Marker been added!")}

        {/* Add Marker */}
        <Marker position={{ lat: mark_lat, lng: mark_lng }} />
      </GoogleMap>
    );
  }
};

Map.defaultProps = {
  zoomLevel: 14,
  map_lat: 50,
  map_lng: -100,
  mark_lat: 50,
  mark_lng: -100,
};

export default Map;

Extra Information:

As you may noticed, I have console log and warn to tell the order of render, from my understanding,

Marker seems been added before Map fully loaded.

Debug Result: Marker been added before Map onLoad been called.

And I do managed render the marker on the map manually (local host):

  1. delete the Marker in run time and save changes, (So let the Map finish load first.)

  2. add Marker. (Map is already finished loading)

And now I got the marker, but it will not be here next time.

Manually Add Marker After Map Rendered, The Marker appear.

How can I sort and reduce the object base on this sample data from javascript array?

The date and time are integers, I would like to sort and reduce them base on up to date format like date should be up to date and military time should be up to date too. All values are distinct base on there object id

let arr = [
            {"id": 1, "date": 20220518, "time": 1700},
            {"id": 1, "date": 20220518, "time": 1500},
            {"id": 1, "date": 20220518, "time": 2200},
            {"id": 1, "date": 20220517, "time": 2300},
            {"id": 2, "date": 20220518, "time": 1500},
            {"id": 2, "date": 20220516, "time": 2100},
            {"id": 3, "date": 20220518, "time": 1400},
            {"id": 3, "date": 20220517, "time": 1900},
            {"id": 3, "date": 20220518, "time": 1900},
            {"id": 4, "date": 20220517, "time": 1900},
            {"id": 4, "date": 20220516, "time": 1300},
            {"id": 5, "date": 20220516, "time": 1600}
        ]
    
    
    
 // Result should be like this
 let arr = [
            {"id": 1, "date": 20220518, "time": 2200},
            {"id": 2, "date": 20220518, "time": 1500},
            {"id": 3, "date": 20220518, "time": 1900},
            {"id": 4, "date": 20220517, "time": 1900},
            {"id": 5, "date": 20220516, "time": 1600}
        ]

Correctly Map API response in react.js

i have been able to make the api and and confirmed the response on console.
I have also been able to filter out the valuable element needed from the response.

  1. My current issue right now is to map the values into a corresponding html element.
    Please see my code. I am working with react and Next.js

  2. Also can someone help me, say i want to map multiple response using this method
    props.entry?.map((enties, i) => () What is the best practise for this.

Thanks very much, i am a big newbie to javascript.

import React, { Component } from "react"
import { Octokit } from "@octokit/core"

const token = "***********************4571B*";
const id = "***********************e911c*";
// Octokit.js
// https://github.com/octokit/core.js#readme

class Dairy extends Component{
    constructor(props){
        super(props);
        this.state = {
          entry: [],
        }
      }
      async componentDidMount()  {
      const octokit = new Octokit({
        auth: token
      })
      
       const response = await octokit.request('GET /gists/{gist_id}', {
        headers: {
            accept: 'application/vnd.github.v3+json',
          },
        gist_id: id,
        
      })
      console.log(response);
      //Below are the values i need from the response
      console.log(response.data.description);
      console.log(response.data.files.ahmed.content);
      console.log(response.data.created_at);

      this.setState({entry: [response.data]})

    }
  render(){
          //here's where i want to map the values.
    return(
       <div>
         
           <div class="rounded-lg border border-stone-800 text-stone-100 bg-opacity-20 bg-stone-800 p-8">
               <h3 class="font-am text-2xl mb-5">{entry.data.description}</h3><div class="space-y-10"><a href="https://www.goodreads.com/book/show/13589182-mastery" target="_blank" rel="noopener noreferrer" class="content-card block hover:cursor-pointer text-stone-300 hover:text-stone-400 group">
               <div class="flex justify-between items-center"><div class="text-lg font-medium mb-1 text-stone-100 group-hover:text-stone-400 transition-colors duration-300">{entry.data.files.ahmed.content}</div>
               <div class="font-fanwood italic text-lg text-stone-400 group-hover:text-stone-500 transition-colors duration-300">{entry.data.created_at}</div></div>
               <div class="text-sm text-stone-400 group-hover:text-stone-500 transition-colors duration-300">written by Robert Greene</div></a></div></div> 
       </div>
    )}
}

export default Dairy;

why this code executes properly if and only if I call setTimeOut() function and the code doesn’t do its aim exactly without callng it? [duplicate]

app.get("/", function(req, res) {
  var posts = [];
  Post.find({}, function(err, arr) {
    if (err) {
      console.log("error");
    } else {
      posts = arr;
    }
  });
  // res.render("home",{par:par,posts:posts})
  setTimeout(function() {
    res.render("home", {
      par: par,
      posts: posts
    })
  }, 300);
});

the code only does its aim when using setTimeout function even if the function inside the setTimeout is the same commented function that doesnt work properly

I´m trying to create elements dinamically on javascript and inserting them on my HTML, but the tag just don´t work

I´m working on a for that create HTML elements than insert them into my page dinamically.

for (let i = 0; i < 26; i++) {
    var res2 = document.getElementById("res2")

    var divCriada = document.createElement("div")
    divCriada.className = "divname"
    divCriada.innerHTML = "abc"

    res2.appendChild(divCriada)
    
    var input   = document.createElement("input")
    input.className = "input"

    let divInserida= document.getElementsByClassName("divname")
    divInserida[i].appendChild(input)

    var br = document.createElement("br")
    res2.appendChild(br)
}

Notice that, the code is doing exactly what it was made for:

https://i.stack.imgur.com/iI5lk.png

All 26 divs are being created correctly, but the line break just don´t work! you can see right ahead!

https://i.stack.imgur.com/974lD.png

I don´t know what to do, i don´t find any answer anywhere =(

i´m new to this world, maybe it could be a gross mistake by me, but if you find it i would aprecciate a lot if you explain what you did and why mine is not working.

how to access async return externally [duplicate]

im new to javascript and struggling with the concepts, how do i access the return value of the async function outside of it, i have tried a .then method but it only returns undefined… this is my code, i want to assign the result to the contractNumber variable outside of the async function so i can pass it to another function and also console.log the result externally… im coming over from learning python so im super confused

const inquirer = require('inquirer')


async function getContract() {
    await inquirer.prompt({
        type: 'input',
        name: 'retrieveContract',
        message: "Enter contract adress: ",
    })
    .then(answer => {
        console.log(`Targetting: ${answer.retrieveContract}`);
        results = answer.retrieveContract
        return results
    }); 
}

getContract()

contractNumber = results

TypeError: Room.findOne is not a function

I just learning how to build a database by using
Im trying to add data to mongoDB and using the .findOne function, but I’m getting this error. is findOne a function in MongoDB?

My Goal is I trying to build a full stack mobile application and using mongoDB for database. FrontEnd is flutter. I’m trying to send data from flutter to mongoDB using socket.io.

You might ask yourself I’m using socket.io if I just need to save data to MongoDB. Well, The application building is game where multiple users can Join a room and interact with each other.

Here is the versions that using to build these backend "mongoose": "^6.3.3", "socket.io": "^2.3.0"

TypeError: Room.findOne is not a function
    at Socket.<anonymous> (/Users/Paul/Documents/server/Index.js:27:45)
    at Socket.emit (node:events:390:28)
    at /Users/Paul/Documents/server/node_modules/socket.io/lib/socket.js:528:12
    at processTicksAndRejections (node:internal/process/task_queues:78:11)

Index.js
Here is my main file

const express = require("express");
var http = require("http")
const app = express();
const port = process.env.PORT || 3000;
var server = http.createServer(app);
const mongoose = require("mongoose");
const Room = require('./models/Room');
//adding socket IO and passing the variable server to it.
var io = require("socket.io")(server);

//middleware
app.use(express.json());

//connecting to MongoDB
const DB = 'mongodb+srv://user:[email protected]/?retryWrites=true&w=majority';

mongoose.connect(DB).then(() => {
    console.log('Connection Successful!');
}).catch((e) =>{
    console.log(e);
})

io.on('connection', (socket) => {
    console.log('connected!');
    socket.on('create-game', async({nickname, name, numRounds, occupancy}) => {
        try {
            const existingRoom = await Room.findOne({name});
            if(existingRoom){
                socket.emit('notCorrectGame', 'Room with that name already exists!');
                return;
            }
            let room = new Room();
            const word = getWord();
            room.word = word;
            room.roomName = roomName;
            room.occupnacy = occupnacy;
            room.numRounds = numRounds;

            let player = {
                socketID: socket.id,
                nickname,
                isPartyLeader: true,
            }
            room.players.push(player);
            room = await room.save();
            socket.join(room);
            io.to(roomName).emit('updateRoom', room);

        } catch (error) {
            console.log(error);
        }
    })
})

server.listen(port, "0.0.0.0", () => {
    console.log('Server started and running on port ' + port);
})

Player.js

const mongoose = require('mongoose');

const PlayerSchema = new mongoose.Schema({
    nickname: {
        type: String,
        trim: true,
    },
    socketID: {
        type: String,
    },
    isPartyLeader: {
        type: Boolean,
        default: false,
    },
    points: {
        type: Number,
        default: 0,
    }
})

const playermodel = mongoose.model('Player', PlayerSchema);
module.exports = {playermodel, PlayerSchema}

Room.js

const mongoose = require("mongoose");
const { PlayerSchema } = require("./Player");

var roomSchema = new mongoose.Schema({
  word: {
    required: true,
    type: String,
  },
  name: {
    required: true,
    type: String,
    unique: true,
    trim: true,
  },
  occupancy: {
    required: true,
    type: Number,
    default: 4
  },
  maxRounds: {
    required: true,
    type: Number,
  },
  currentRound: {
    required: true,
    type: Number,
    default: 1,
  },
  players: [PlayerSchema],
  isJoin: {
    type: Boolean,
    default: true,
  },
  turn: PlayerSchema,
  turnIndex: {
    type: Number,
    default: 0
  }
});

const gameModel = new mongoose.model('Room', roomSchema);
module.exports = {gameModel, roomSchema};

I honestly cant figure out why I encountering this error. Maybe, I just need a second eyes to help me out.

Can anyone help with this error? Please and Thank you in advance!

How to add multiple forms elements to a json file

So i have questions.json file that i created before. Im trying to design basic online quiz app i almost finished but i want to add couple more moduls so it can look better

{
"response_code": 0,
"results": [
  {
    "category": "CSS",
    "difficulty": "Vize",
    "question": "CSS'in açılımı nedir?",
    "correct_answer": "Cascading Style Sheets  ",
    "incorrect_answers": ["Creative Style Sheets", "Colorful Style Sheets", "Computer Style Sheets"]
  },{
    "category": "React",
    "difficulty": "Final",
    "question": "React componentlerini belli durumlara göre render'layan operatör?",
    "correct_answer": "&&",
    "incorrect_answers": ["||", "??", "::"]
  },

]}

I created 5 input forms for that 5 variable and i created a button with handleSubmit1 function so how can i add the values i wrote in these input forms to my json file?

const AdminPanel =()=>{
const [newQuestion, setNewQuestion] = useState("");
const [questionCategory, setQuestionCategory] = useState("");
const [questionDifficulty, setQuestionDifficulty] = useState("");
const [correctAnswer, setCorrectAnswer] = useState("");
  const [incorrectAnswer, setIncorrectAnswer] = useState("");
  const handleSubmit1 = (e) => {
    e.preventDefault();
  };
return (
    <div>
      <div>
        <input
          type="text"
          placeholder="  Question: :"
          value={newQuestion}
          onChange={(e) => setNewQuestion(e.target.value)}
        />
        <input
          type="text"
          placeholder="  Question Category :"
          value={questionCategory}
          onChange={(e) => setQuestionCategory(e.target.value)}
        />
        <input
          type="text"
          placeholder="  Question difficulty :"
          value={questionDifficulty}
          onChange={(e) => setQuestionDifficulty(e.target.value)}
        />
        <input
          type="text"
          placeholder="  Correct Answer :"
          value={correctAnswer}
          onChange={(e) => setCorrectAnswer(e.target.value)}
        />
        <input
          type="text"
          placeholder="  Incorrect Answer :"
          value={incorrectAnswer}
          onChange={(e) => setIncorrectAnswer(e.target.value)}
        />
        <button className="button-3" onClick={handleSubmit1}>
          Add Question
        </button>
      </div>
</div>
);
};
export default AdminPanel;

unexpected bootstrap theme quirks

I bought a bootstrap template a while back from a guy who’s site is now gone. On one of the pages,
there are 9 tiles (masonry), each of which I am using for different sub parts. As a sanity guard, I
numbered all the tiles so I could tell them apart both in the code and on the screen. This works
fine until I get to the 9th and last tile, where the number 9 looks like a lower case letter g.
At first that’s what I thought it was, but then I did a comparison test. Sure enough, there is a
small but subtle difference between the lowercase letter g and the number 9, specifically, a little
serif poking above the back of the letter g.

But now that that’s solved, it also means the 9’s sit lower than the 8 and 0 sits between them in
height. Here’s a screenshot:number font

What can I do at this late date to get sensible looking numbers?

I was also surprised to see that once named and ordered, the tiles do not stay in that order.
If I can target them correctly with my variables, maybe I can live with that, but just in case I’d
like to know how to stop that, too. Thanks.

Auto slider javascript

I made an autoplay slider for a landing page and I want it to resume the autoplay function when it’s not being interacted with. For desktop, I have it set to clear the interval when on mouseenter and run the autoplay function on mouseleave. On mobile devices, I have it set to clear interval on touchstart and then a settimeout that starts the autoplay function. This works but I noticed that if someone touches multiple radio buttons in quick succession it bugs out and acts as if it calls multiple autoplay functions. How would I stop that from happening or is there a better way to structure it to prevent this from happening. Thank you.

Javascript

const slideContainer = document.querySelector('.container');
const slider = document.querySelector('.slides');
const nextBtn = document.getElementById('next-btn');
const prevBtn = document.getElementById('prev-btn');
const interval = 4300;
const radioBtns = document.querySelectorAll('.radio-btn')
const radioLabels = document.getElementsByClassName('manual-btn');
const slideContent = document.querySelectorAll('.slide-content');

let slides = Array.from(document.querySelectorAll('.slide'));

let index = 1;
let slideId;
let radioMax = slides.length

const firstClone = slides[0].cloneNode(true);
firstClone.childNodes[3].remove();
const lastClone = slides[slides.length - 1].cloneNode(true);
lastClone.childNodes[3].remove();


firstClone.id = 'first-clone';
lastClone.id = 'last-clone';

slider.append(firstClone);
slider.prepend(lastClone);

const slideWidth = slides[index].clientWidth;

slider.style.transform = `translateX(${-slideWidth * index}px)`;

const autoPlay = () => {
  slideId = setInterval(() => {
    moveToNextSlide();
  }, interval);
};

radioBtns.forEach(radioBtn => {
  radioBtn.addEventListener('click', () => {
    slider.style.transform = `translateX(${-slideWidth * radioBtn.value}px)`;
    slider.style.transition = '1.3s ease-out';
    index = radioBtn.value;
    clearInterval(slideId);

    for (var i = 0; i < radioLabels.length; i++) {
      radioLabels[i].classList.remove('active')
    }

    radioLabels[index - 1].classList.add('active') 

    fadeStart();
  })
})

const getSlides = () => document.querySelectorAll('.slide');

slider.addEventListener('transitionend', () => {
  fadeEnd();

  slides = getSlides();
  if (slides[index].id === firstClone.id) {
    slider.style.transition = 'none';
    index = 1;
    slider.style.transform = `translateX(${-slideWidth * index}px)`;
  }

  if (slides[index].id === lastClone.id) {
    slider.style.transition = 'none';
    index = slides.length - 2;
    slider.style.transform = `translateX(${-slideWidth * index}px)`;
  }
});

function fadeEnd() {
  slideContent.forEach(singleContent => {
    singleContent.classList.remove('fade-animation-start');
    singleContent.classList.add('fade-animation-up');
  }) 
}

function fadeStart() {
  slideContent.forEach(singleContent => {
    singleContent.classList.remove('fade-animation-up');
    singleContent.classList.add('fade-animation-start');
  }) 
}

const moveToNextSlide = () => {
  slides = getSlides();
  if (index >= slides.length - 1) return;
  index++;
  slider.style.transition = '.7s ease-out';
  slider.style.transform = `translateX(${-slideWidth * index}px)`;

  if(slides[index].id !== firstClone.id & (slides[index].id !== lastClone.id)) {
    radioLabels[index - 2].classList.remove('active');
    radioLabels[index - 1].classList.add('active');
  }

  if(slides[index].id === firstClone.id) {
    radioLabels[(radioMax) - 1].classList.remove('active')
    radioLabels[0].classList.add('active')
  }

  fadeStart();
};

const moveToPreviousSlide = () => {
  if (index <= 0) return;
  index--;
  slider.style.transition = '.7s ease-out';
  slider.style.transform = `translateX(${-slideWidth * index}px)`;

  if(slides[index].id !== firstClone.id & (slides[index].id !== lastClone.id)) {
    radioLabels[index].classList.remove('active');
    radioLabels[index - 1].classList.add('active');
  }

  if (slides[index].id === lastClone.id) {
    radioLabels[0].classList.remove('active')
    radioLabels[(radioMax) - 1].classList.add('active')
  }

  fadeStart();
};

slideContainer.addEventListener('mouseenter', () => {
  clearInterval(slideId);
});

slideContainer.addEventListener('mouseleave', function() {
  clearInterval(slideId);
  autoPlay();
});
slideContainer.addEventListener('touchstart', function() {
  clearInterval(slideId);
  setTimeout(() => {
    autoPlay();
  }, interval);
})

nextBtn.addEventListener('click', moveToNextSlide);
prevBtn.addEventListener('click', moveToPreviousSlide);

autoPlay();

HTML

<body>
    <div class="container">
        <div class="slider-container">
            <div class="slides">
                <div class="slide-btns">
                    <input type="radio" name="radio-btn" id="radio1" value="1" class="radio-btn">
                    <input type="radio" name="radio-btn" id="radio2" value="2" class="radio-btn">
                    <input type="radio" name="radio-btn" id="radio3" value="3" class="radio-btn">
                    <input type="radio" name="radio-btn" id="radio4" value="4" class="radio-btn">
                  </div>
                <div class="slide">
                    <div class="img-wrapper">
                        <img src="./img/construction_1.jpeg" alt="">
                        <div class="overlay"></div>
                    </div>
                    <div class="slide-content fade-animation-up">
                        <h2>TJBuilders</h2>
                        <h5>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quis quisquam repudiandae accusantium sit eius accusamus?</h4>
                        <button class="btn-light">
                            <a href="contact.html">
                                Get Free Quote!
                            </a>
                        </button>
                    </div>
                </div>
                <div class="slide">
                    <div class="img-wrapper">
                        <img src="./img/construction_2.jpeg" alt="">
                        <div class="overlay"></div>
                    </div>
                    <div class="slide-content">
                        <h2>TJBuilders</h2>
                        <h5>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quis quisquam repudiandae accusantium sit eius accusamus?</h4>
                        <button class="btn-light">
                            <a href="contact.html">
                                Get Free Quote!
                            </a>
                        </button>
                    </div>
                </div>
                <div class="slide">
                    <div class="img-wrapper">
                        <img src="./img/construction_3.jpeg" alt="">
                        <div class="overlay"></div>
                    </div>
                    <div class="slide-content">
                        <h2>TJBuilders</h2>
                        <h5>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quis quisquam repudiandae accusantium sit eius accusamus?</h4>
                        <button class="btn-light">
                            <a href="contact.html">
                                Get Free Quote!
                            </a>
                        </button>
                    </div>
                </div>
                <div class="slide">
                    <div class="img-wrapper">
                        <img src="./img/construction_4.jpeg" alt="">
                        <div class="overlay"></div>
                    </div>
                    <div class="slide-content">
                        <h2>TJBuilders</h2>
                        <h5>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quis quisquam repudiandae accusantium sit eius accusamus?</h4>
                        <button class="btn-light">
                            <a href="contact.html">
                                Get Free Quote!
                            </a>
                        </button>
                    </div>
                </div>
            </div>
            <div class="navigation-manual">
                <label for="radio1" id="radio-label1" class="manual-btn active"></label>
                <label for="radio2" id="radio-label2" class="manual-btn"></label>
                <label for="radio3" id="radio-label3" class="manual-btn"></label>
                <label for="radio4" id="radio-label4" class="manual-btn"></label>
              </div>
            <div class="slide-controls">
                <button id="prev-btn">
                    <i class="fas fa-chevron-left"></i>
                </button>
                <button id="next-btn">
                    <i class="fas fa-chevron-right"></i>
                </button>
            </div>
        </div>
    </div>
    
    <script src="https://kit.fontawesome.com/90872ef2e4.js" crossorigin="anonymous"></script>
    <script src="./js/app.js"></script>
</body>

How do I store the scores, grades and comment enter into database?

I have created a “grading table” that declared my low marks, high marks, grade and comment. I also have my result table with the following column label ‘id’,’subjectid’,’studentid’,’grades’, ‘comments’; to store the input results. My problem now is to create the php code to store what ever score that is entered and compare it with the assigned grades in the database. Below is my code

{
        
        $marks=array();
    $class=$_POST['class'];
    $studentid=$_POST['studentid']; 
    $mark=$_POST['marks'];
    $grades=$_POST['grades'];
    $comments=$_POST['comments'];
    //coding
    
    $sum=$mark*10; //total marks
        $avg=$sum;
        if($avg>=0&&$avg<=50)
            $grades="Fail";
        if($avg>50&&$avg<=70)
            $grades="C";
        if($avg>70&&$avg<=80)
            $grades="B";
        if($avg>80&&$avg<=90)
            $grades="A";
        if($avg>90)
            $grade="E";
    //end
    
    
    
     $stmt = $dbh->prepare("SELECT tblsubjects.SubjectName,tblsubjects.id FROM tblsubjectcombination join  tblsubjects on  tblsubjects.id=tblsubjectcombination.SubjectId WHERE tblsubjectcombination.ClassId=:cid order by tblsubjects.SubjectName");
     $stmt2=$dbh->prepare("SELECT id,StudentId,ClassId,SubjectId,marks,grades,comments from tblresult join grading on marks between lowmark and himark");
    
     $stmt->execute(array(':cid' => $class));
      $sid1=array();
     while($row=$stmt->fetch(PDO::FETCH_ASSOC))
     {
    
    array_push($sid1,$row['id']);
       } 
      
    for($i=0;$i<count($mark);$i++){
        $mar=$mark[$i];
      $sid=$sid1[$i];
      //my code 
    //$totalmarks=$marks*10;
    
    $sql="INSERT INTO  result(StudentId,ClassId,SubjectId,marks,grades,comments) VALUES(:studentid,:class,:sid,:marks,:grades,:comments)";
    $query = $dbh->prepare($sql);
    $query->bindParam(':studentid',$studentid,PDO::PARAM_STR);
    $query->bindParam(':class',$class,PDO::PARAM_STR);
    $query->bindParam(':sid',$sid,PDO::PARAM_STR);
    $query->bindParam(':marks',$mar,PDO::PARAM_STR);
    $query->bindParam(':grades',$grades,PDO::PARAM_STR);
    $query->bindParam(':comments',$comments,PDO::PARAM_STR);
    $query->execute();
    $lastInsertId = $dbh->lastInsertId();
    if($lastInsertId)
    {
    $msg="Result added successfully";
    }
    else 
    {
    $error="Please correct the error";
    }
    }
    }
    ?>
    
      <!-- My Grading starts from here -->
       
    <!-- grading stop here -->  
    
    
            <script>
    function getStudent(val) {
        $.ajax({
        type: "POST",
        url: "get_student.php",
        data:'classid='+val,
        success: function(data){
            $("#studentid").html(data);
            
        }
        });
    $.ajax({
            type: "POST",
            url: "get_student.php",
            data:'classid1='+val,
            success: function(data){
                $("#subject").html(data);
                
            }
            });
    }
        </script>
    <script>
    
    function getresult(val,clid) 
    {   
        
    var clid=$(".clid").val();
    var val=$(".stid").val();;
    var abh=clid+'$'+val;
    //alert(abh);
        $.ajax({
            type: "POST",
            url: "get_student.php",
            data:'studclass='+abh,
            success: function(data){
                $("#reslt").html(data);
                
            }
            });
    }
    </script>
    
    
        </head>
        <body class="top-navbar-fixed">
            <div class="main-wrapper">
    
                <!-- ========== NAVBAR ========== -->
      <?php include('includes/topbar.php');?> 
                <!-- ========== SIDEBARS & MAIN CONTENT ========== -->
                <div class="content-wrapper">
                    <div class="content-container">
    
                        <!-- ========== LEFT SIDEBAR ========== -->
                       <?php include('includes/leftbar.php');?>  
                        <!-- /.left-sidebar -->
    
                        <div class="main-page">
    
                         <div class="container-fluid">
                                <div class="row page-title-div">
                                    <div class="col-md-6">
                                        <h2 class="title">Result Page</h2>
                                    
                                    </div>
                                    
                                                               </div>
                                <!-- /.row -->
                                <div class="row breadcrumb-div">
                                    <div class="col-md-6">
                                        <ul class="breadcrumb">
                                            <li><a href="dashboard.php"><i class="fa fa-home"></i> Home</a></li>
                                    
                                            <li class="active">Student Result</li>
                                        </ul>
                                    </div>
                                 
                                </div>
                                <!-- /.row -->
                            </div>
                            <div class="container-fluid">
                               
                            <div class="row">
                                        <div class="col-md-12">
                                            <div class="panel">
                                               
                                                <div class="panel-body">
    <?php if($msg){?>
    <div class="alert alert-success left-icon-alert" role="alert">
     <strong>Good job!</strong><?php echo htmlentities($msg); ?>
     </div><?php } 
    else if($error){?>
        <div class="alert alert-danger left-icon-alert" role="alert">
                                                <strong>Try again!</strong> <?php echo htmlentities($error); ?>
                                            </div>
                                            <?php } ?>
                                                    <form class="form-horizontal" method="post">
    
     <div class="form-group">
    <label for="default" class="col-sm-2 control-label">Class</label>
     <div class="col-sm-10">
     <select name="class" class="form-control clid" id="classid" onChange="getStudent(this.value);" required="required">
    <option value="">Select Class</option>
    <?php $sql = "SELECT * from classes";
    $query = $dbh->prepare($sql);
    $query->execute();
    $results=$query->fetchAll(PDO::FETCH_OBJ);
    if($query->rowCount() > 0)
    {
    foreach($results as $result)
    {   ?>
    <option value="<?php echo htmlentities($result->id); ?>"><?php echo htmlentities($result->ClassName); ?></option>
    <?php }} ?>
     </select>
                                                            </div>
                                                        </div>
    <div class="form-group">
                                                            <label for="date" class="col-sm-2 control-label ">Student Name</label>
                                                            <div class="col-sm-10">
                                                        <select name="studentid" class="form-control stid" id="studentid" required="required" onChange="getresult(this.value);">
                                                        </select>
                                                            </div>
                                                        </div>
    
                                                        <div class="form-group">
                                                          
                                                            <div class="col-sm-10">
                                                        <div  id="reslt">
                                                        </div>
                                                            </div>
                                                        </div>
                                                        
    <div class="form-group">
                                                            <label for="date" class="col-sm-2 control-label">Subjects</label>
                                                            <div class="col-sm-10">
                                                        <div  id="subject">
                                                        </div>
                                                            </div>
                                                        </div>
    
    
                                                        
                                                        <div class="form-group">
                                                            <div class="col-sm-offset-2 col-sm-10">
                                                                <button type="submit" name="submit" id="submit" class="btn btn-primary">SUBMIT</button>
                                                            </div>
                                                        </div>
                                                    </form>