JavaScript POST non-API request with repeated keys in payload

Javascript. POST request. It is not an API request (axios or fetch), but the old classical request.

I need a payload like ...&_selected_action=5&_selected_action=10.
So I think I cannot use a form submitting technique here.
With a single occurence ...&_selected_action=5 I am able to do it, everything works well.
For the repeated value I can create the string by hand or by URLSearchParams().toString() but I am not able to send it.

Any idea?

More details. I need create this request in Django+Vue application which partially replaces the old school Django Admin. The ListView is replaced using Vue and now I want to reuse the actions where Django Admin uses Post request formatted as above. So with single selected row in list I am able to do it, but with 2+ selected rows I cannot find a good way how to do it.

Cannot access ‘usagePrice’ before initialization

I have a script that I’m using to calculate the price of a selected field

When i run the function ‘calculateTotal()’ i get this error “Cannot access ‘usagePrice’ before initialization”.

Here is my code:

// Returns total for step 1
const usagePrice = () => {
    const field = document.querySelector('input[name="usage"]:checked');
    const subField = document.querySelector('input[name="varifocal-lenses"]:checked');

    let price = field.dataset.price;
       

    if (field.value == 'varifocal') {
        
        price = subField.dataset.price;
    }

    console.log('Usage price: ' + price);
    return price;
}

// Adds all totals together
const calculateTotal = () => {
    const usagePrice = usagePrice();
    const prescriptionPrice = prescriptionPrice();
    const lensPackagePrice = lensPackagePrice();
    const lensTypePrice = lensTypePrice();

    const total = usagePrice + prescriptionPrice + lensPackagePrice + lensTypePrice;

    return total;
}


console.log(calculateTotal());

Can anyone explain whats going wrong? Thank you in advance.

How to loop over again an array when it finishes? JavaScript

Here is my code:

useEffect(() => {
    playerRef.current.seekTo(convertedflat[currentTimeIndex], 'seconds');
  });
  return (
    <>
      <main>
        <div className={style.main_container}>
          <NavBar />

          <div className={style.heronext}>
            <div className={style.hero_container}>
              <ReactPlayer
                ref={playerRef}
                playing
                controls={true}
                url={`videos/${episList[currentEpisodeIndex]}.mkv`}
                width="90%"
                height="55rem"
                />
               </div>

              <button
              className={style.next}
              onClick={() => {
                setCurrentTimeIndex((prevTimeIndex) => prevTimeIndex + 1) %
                  convertedflat.length;

                setcurrentEpisodeIndex((prevTimeIndex) => prevTimeIndex + 1) %
                  convertedflat.length;

                console.log(currentTimeIndex);
                console.log(currentEpisodeIndex);
              }}
            >
              Next
            </button>

basically when you click on the next button it moves to the next timestamp until the array finishes. but I want to it starts again when the array list is finished.Currently when the array navigation is finished it shows error.

I used % length but it doesnt work.
Here is the error message when the list is finished:

TypeError: Failed to set the ‘currentTime’ property on ‘HTMLMediaElement’: The provided double value is non-finite.

How to render only one component after changing the state from api?

I’m trying to create an interface to be able to monitor the outputs of a relay board.
When the page is loaded, the status of the output is set by changing the image of the component. I want read the status of the outputs every 1 second and update the relative component.
If I open another tab where I go to change the status of the output automatically I have to change the status of the first tab as well.
I don’t know how to make react render only the component that has changed

import React, { useState, useEffect } from 'react'
import EventBus from "../common/EventBus";
import api from "../services/api";
import Device from "../components/Device"
const serverLink = "http://localhost:8080";

const Devices = () => {
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(false);
    const [errorCode, setErrorCode] = useState("")
    const [state, setState] = useState()
    const [refreshInterval, setRefreshInterval] = useState(4000)
    async function setDevice(_id, outId, value) {
        try {
            const response = await api({ url: `${serverLink}/api/device/setdevice`, method: "POST", data: { _id: _id, outId: outId, value: value } })
            if (response.data.status === "error") {
                setError(true)
                setErrorCode(response.data.description)
                setLoading(false)
            }
        } catch (error) {
            const _content =
                (error.response &&
                    error.response.data &&
                    error.response.data.message) ||
                error.message ||
                error.toString();
            setErrorCode(_content);
            if (error.response && error.response.status === 403) {
                EventBus.dispatch("logout");
            }
        }
    }
    async function getStatus() {
        try {
            const response = await api.get(`${serverLink}/api/device/getstatus`)
            if (response.data.status === "error") {
                setError(true)
                setErrorCode(response.data.description)
                setLoading(false)
            } else {
                setState(response.data.data)
                setLoading(false)
            }
        } catch (error) {
            const _content =
                (error.response &&
                    error.response.data &&
                    error.response.data.message) ||
                error.message ||
                error.toString();
            setErrorCode(_content);
            if (error.response && error.response.status === 403) {
                EventBus.dispatch("logout");
            }
        }
    }

     useEffect(() => {
         getStatus()
         const interval = setInterval(getStatus, refreshInterval)
         return () => clearInterval(interval);
     }, []);
    return (
        <div className='conteiner-rw'>
            {loading ? "caricamento..." : error ? <p>{errorCode}</p> :(
                state.map((dev) => {
                    return dev.out.map((el, index) => {
                        return <Device key={index} {...el} _id={dev._id} setDevice={setDevice} />
                    })
                }))
            }
        </div>
    )
}

export default Devices

The device component

import React, { useState, useEffect } from 'react';
import image from "../assets/image/image"

const Device = ({ id, _id, name, type, value, setDevice }) => {
    const [state, setState] = useState(value)
    const changeState = () => {
        if (state == 1) {
            setState(0)
            setDevice(_id, id, 0)
        } else if (state == 0) {
            setState(1)
            setDevice(_id, id, 1)
        }

    }

    return (
        <div className='device conteiner-cl' onClick={() => changeState()}>
            <img src={state == 1 ? image.lamp_on : image.lamp_off} alt={name} className='icon' />
            {
                name
            }
        </div>

    )
}

export default Device

The api response

{
    "status": "ok",
    "data": [
        {
            "_id": "619e17af1479f1846c8afaee",
            "name": "dev1",
            "ip": "192.168.0.50",
            "descr": "denkovi",
            "channel": "",
            "type": "denkovi",
             "out": [
                {"id": 1,"name": "output1","value": "0"},
                {"id": 2,"name": "output2","value": "0"},
                {"id": 3,"name": "output3","value": "0"},
                {"id": 4,"name": "output4","value": "0"},
                {"id": 5,"name": "output5","value": "0"},
                {"id": 6,"name": "output6","value": "0"},
                {"id": 7,"name": "output7","value": "0"},
                {"id": 8,"name": "output8","value": "0"},
                {"id": 9,"name": "output9","value": "0"},
                {"id": 10,"name": "output10","value": "0"},
                {"id": 11,"name": "output11","value": "0"},
                {"id": 12,"name": "output12","value": "0"},
                {"id": 13,"name": "output13","value": "0"},
                {"id": 14,"name": "output14","value": "0"},
                {"id": 15,"name": "output15","value": "0"},
                {"id": 16,"name": "output16","value": "0"}
                        ]
        },
        {
            "_id": "619e17af1479f1846c8afaef",
            "name": "dev2",
            "ip": "192.168.0.50",
            "descr": "denkovi",
            "channel": "",
            "type": "denkovi",
            "out": [
                {"id": 1,"name": "output1","value": "0"},
                {"id": 2,"name": "output2","value": "0"},
                {"id": 3,"name": "output3","value": "0"},
                {"id": 4,"name": "output4","value": "0"},
                {"id": 5,"name": "output5","value": "0"},
                {"id": 6,"name": "output6","value": "0"},
                {"id": 7,"name": "output7","value": "0"},
                {"id": 8,"name": "output8","value": "0"},
                {"id": 9,"name": "output9","value": "0"},
                {"id": 10,"name": "output10","value": "0"},
                {"id": 11,"name": "output11","value": "0"},
                {"id": 12,"name": "output12","value": "0"},
                {"id": 13,"name": "output13","value": "0"},
                {"id": 14,"name": "output14","value": "0"},
                {"id": 15,"name": "output15","value": "0"},
                {"id": 16,"name": "output16","value": "0"}
            ]
        }
    ]
}

Detect if the position of a div crosses the center of the viewport

I am trying to observe and detect if the position of a div crosses the center of my viewport on the y-axis. If so a function should be fired.
I am not scrolling or dragging the element so I can’t use an event listener that listen to those events.
Does anyone know an approach that I could follow?
Please no jQuery solutions, I am using Vue3 so I would wan’t to use plain javascript.

moment js not showing local time it’s showing same in the Database

how to display createdAt field date according to the local timezone. i have tried it’s only working for localhost when I upload it on the server it’s showing createdAt field data UTC format.

here is my code

dateFormatwithSec(date_time) {

    const testDateUtc = moment.utc(date_time);
    const localDate = moment(testDateUtc).local();
    return localDate.format('YYYY-MM-DD HH:mm:ss');
},

why it’s not providing the right output on the server.

Blob file not open in Edge browser on Iphone IOS mobile

Hi All I am not able to dowonload PDF file on Iphone edge browser below is my code snippet in angular.

    const fileName = file.name + '.' + file.data_type;
      const dataType = res.type;
      const binaryData = [];
      binaryData.push(res);
      const blob = new Blob(binaryData, { type: 'application/pdf'});
      // IE
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, fileName);
      } else {
        // other browser
        const downloadLink = document.createElement('a');
        const url = window.URL.createObjectURL(blob);
        document.body.appendChild(downloadLink);
        downloadLink.href = url;
        downloadLink.target = '_blank';
        downloadLink.download = fileName;
        downloadLink.click();
       
      }

It is working on all other browser and devic.Not only working on Edge browser of Iphone

How can I generate all the combos taking into account the weight of each item in Javascript? [duplicate]

I have been struggling for several days with the following algorithm I need.

What I need to generate are the totality of combos taking into account the weight in their generation.

// Generate composition depending on weight.
// The weight is a value from 1 to 100, representing the importance in the generation.
// ex.: A layer with 1% should only display 1% of the total generated.

const layers = [
    [
    { id: 1, weight: 1 },   // Shows 1 time
    { id: 2, weight: 9 },   // Shows 9 times
    { id: 3, weight: 15 },  // Shows 15 times
    { id: 4, weight: 25 },  // Shows 25 times
    { id: 5, weight: 50 },  // Shows 50 times
  ],
  [
    { id: "a", weight: 50 },    // Shows 50 times
    { id: "b", weight: 25 },    // Shows 25 times
    { id: "c", weight: 15 },    // Shows 15 times
    { id: "d", weight: 9 },     // Shows 9 times
    { id: "e", weight: 1 },     // Shows 1 times
  ], 
    [
    { id: "_", weight: 15 },    // Shows 15 times
    { id: "-", weight: 25 },    // Shows 25 times
    { id: ".", weight: 50 },    // Shows 50 times
    { id: ",", weight: 9 },     // Shows 9 times
  ]
  // ... There could be more collections
]

const combTotal = layers[0].length * layers[1].length * layers[2].length // => 100


// Expect result:
 
[ 
  [5, "d", "."], 
  [2, "a", "_"],
  [4, "a", ","],
  // ...
]

Generating the whole composition without weights is simple, but the calculation to take into account the weight is costing me more than it should.

If someone could show me some reference to unlock me, it would be great.

Best regards

IntelliSense not working for dynamically loaded JavaScript files

I have created number of models(separate files) in my NodeJS Project. I am exporting all the files dynamically in single index.js file. Now when I require models folder and try to load the Model Intellisense is not be able to load that Model.

  • Is there any solution to resolve this issue.
  • Expected intellisene Path is const {ModelController} = require('../models')

/models/index.js

'use strict';

const testFolder = './app/models';
const fs = require('fs');
const commons = require('../common');

const ExportsModel = {};
fs.readdirSync(testFolder).forEach((file) => {
  const fileName = file.split('.')[0];
  ExportsModel[commons.capitalizeFirstLetter(fileName) + 'Conrtroller'] = require(`./${fileName}`);
});

// console.info('ExportsModel', ExportsModel);
module.exports = ExportsModel;

/models/station.js

const mongoose = require('../configs/db.configs');
const Schema = mongoose.Schema;

const ModelSchema = new Schema(
  {
    name: { type: String, required: true },
    stationId: { type: Schema.Types.ObjectId, ref: 'station', required: true },
    description: { type: String, required: true },
  },
  { timestamps: true }
);

module.exports = mongoose.model('charger', ModelSchema);

Thank you in advance

VueJS disable outer div scroll and enable again after inner div reached its bottom

I’m doing a webpage with multiple div which placed vertically, and here’s my concept:

  1. When the scrollbar reached the first div bottom, the outer scrollbar will be disabled and enable the second scrollbar
  2. The user have to reach the inner scrollbar bottom in order to enable the outer scrollbar

I tried to found the name as wells as the sample from the Internet, but I can’t really found what I want. So I would like to request any volunteers to help me about my concept.

Opening new window on the latest version of Firefox miss browser tabs

I got a problem with my application, one of the features I have is open a window that has tabs, it works properly on an old version of Firefox 68 and older, the newest one like 91.x.x, it opens a new window but without the toolbar for opening new tabs, Here’s the code I’m using:

const openPage= window.open(Page, "OPP| App", 'location=1,status=1,scrollbars=1, resizable=1, directories=1, toolbar=1, titlebar=1,fullscreen=yes');

how to create view,property in google analytics and cointainer in tag manager on user signup

I am new to google analytics and tag manager

My problem is that i want to create view and property in google analytics when user’s sign up to my website and also i need to create cointainer in Tag manager when user’s sign up to my website

First thing :
i am creating view, property in google analytics using this link developers.google.com/analytics/devguides/config/mgmt/v3/mgmtReference/management/profiles/insert#javascript and cointainer in Tag manager using this link developers.google.com/tag-platform/tag-manager/api/v2/reference/accounts/containers/create
but its only working with my gmail

What i want is :

I want to create View,property,cointainer for different users when they signup.

How can i achive that

Thanks for helping

Note: i am using javascript language

Avoid redirect loop in chrome extension

I’ve made a chrome extension that uses an allow list of urls that you can visit, defined in extension option, if not your are redirected to a defined page.

So let say I only allow the site example.com and when visting any other site it will send me back to example.com, BUT if example.com itself redirect to a login page that’s not on the list it will loop. Of course the best way is to add the login page to the allowed list but if I want to avoid this, are there a better approach to stop a redirect loop?

example of code in content script of the extension:

let homepage = "https://example.com";
let allowlist = "https://example.com";

function TriggerAllowSites() {
    let currentUrl = window.location.href;
    let match = currentUrl.match(allowlist);
    if (match && match.length > 0) {
        console.log("We are allowed here");
    } else {
        window.location.href = homepage;
    }
}

TriggerAllowSites()