Use api data inside a javascript script

I am rendering an EJS template with an array. But inside the script I can’t access the data. How do I access that data inside a script ?

API CODE

app.get('/', (req, res) => {
    var countries = [
        {
            name: 'america',
            cities: [
                'New york',
                'Los Angeles'
            ]
        },
        {
            name: 'india',
            cities: [
                'Delhi',
                'Mumbai'
            ]
        }
    ]
    res.render('home', {
        countries
    });
});

JS SCRIPT

<script>
        function populate(sel1, sel2) {
            console.log('funcc');
            console.log(countries);
        }
    </script>

The error in chrome console is:
Uncaught ReferenceError: countries is not defined

There is “undefined” in my chart created by chart.js

There is an undefined appearing in the chart created by Chart.js v3.7.0 and v2.9.4 as well ass seen in the figure.

and the function generating the graph, div and canvas is (JS) as follows:

    function arrangeForGraph(counts){
        for(var i =0;i<counts.length;i++){
                var divname = document.createElement("div");
                divname.id="div"+i;
                divname.class="chartAreaWrapper;chart";
        var dataname = document.createElement("data");
                var _canvas = document.createElement("canvas");
                _canvas.id="canvas"+i;
                _canvas.height="400";
                _canvas.width="600";
                _label_list = counts[i][4];
        dataname.id=_label_list;
        dataname.value= counts[i][0];
        dataname.style="display:none;"
        dataname.title="countchart"; 
        dataname.text="countsch";
                var ctx = _canvas.getContext("2d");
        ctx.imageSmoothingEnabled = true;
        Chart.plugins.register({id: 'pan', id:'zoom'});
                var myChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: _label_list,
                        datasets: [
                            {
                                label: "Upper Bound",
                                data: counts[i][3],
                                backgroundColor: ['rgba(150, 150, 150, 0.50)'],
                                borderColor: ['rgba(150, 150, 150, 0.50)'],
                                borderWidth: 0.5,
                                pointRadius: 1,
                                fill: 1,
                            },
                            {
                                label: "Lower Bound",
                                data: counts[i][1],
                                backgroundColor: ['rgba(150, 150, 150, 0.50)'],
                                borderColor: ['rgba(150, 150, 150, 0.50)'],
                                borderWidth: 0.5,
                                pointRadius: 1,
                                fill: false,
                            },
                            {
                                label: "Value",
                                order: 1,
                                data: counts[i][0],
                                backgroundColor: 'rgba(75, 192, 192, 0.85)',
                                borderColor: 'rgba(75, 192, 192, 0.85)',
                                borderWidth: 2,
                                pointRadius: 3,
                                fill: false,
                            },
                {
                                label: "Prediction",
                                order: 1,
                                data: counts[i][2],
                                backgroundColor: 'rgba(100, 100, 100, 0.85)',
                                borderColor: 'rgba(100, 100, 100, 0.85)',
                                borderWidth: 2,
                                pointRadius: 3,
                                fill: false,
                            },
                        ]
                    },
                    options: {
            
                                pan: {
                                 enabled: true,
                                 mode: 'xy'
                                 },
                                zoom: {
                                 enabled: true,
                                 drag: true,
                                 speed: 0.1,
                                 threshold: 2,
                                 mode: 'xy'
                                },
            title:{
                  text: "Behaviours",
                  display: true,
                      fontSize: 15
                },
            legend: {
                    display: false},
            elements: {center:{}},
                        responsive: true,
                        scales: {
                            xAxes: [{scaleLabel: {display: true, labelString: 'Date & Time'}}],
                            yAxes: [{scaleLabel: {display: true, labelString: 'Parameter Values'},ticks: {beginAtZero: true}}]
                        }
                    },
                });console.log(myChart);
        document.getElementById("main2").appendChild(divname);
        document.getElementById(divname.id).appendChild(_canvas);
        document.getElementById(_canvas.id).appendChild(dataname);
            };

}

Does anybody point my mistake so I can remove that annoying undefined watermark?

The graph is generated with the array coming from serverside, and if more than 1 array is found in counts then counts.length amounts o graphs are generated without any erorrs except that undefined mark on each graph.

Pan and zoom is not working as well but I think I have to ask another question for that.

Thanks in advance

Why application craches when using express-rate-limit?

I’m using express-rate-limit package version 6.0.1 to limit hits of request an I also had used express-rate-limit documentation found on https://www.npmjs.com/package/express-rate-limit

However when I use this in my app, my application crashes.
I”m not understanding what is going on here. I have search allot for a conclusion but without any results.
Can someone give me an idea of what I’m doing wrong???

...

//Load env vars
dotenv.config({ path: "./config/config.env" });

//Connect to database
connectDB();

const app = express();

//Set Static folder
app.use(express.static(path.join(__dirname, "public")));

// Body Parser
app.use(express.json());

// Cookie parser
app.use(cookieParser());

//Dev logging middleware
if (process.env.NODE_ENV === "development") {
  app.use(morgan("dev"));
}

// File uploading
app.use(fileUpload());

// Sanitize data
app.use(mongoSanitize());

// Set security headers
app.use(helmet());

// Prevent XSS attacks
app.use(xss());

//Rate limiting
const limiter = rateLimit({
  windowMs: 10 * 60 * 1000, // 10 mins
  max: 1,
});

app.use(limiter);

// Prevent http param pollution
app.use(hpp());

app.use(errorHandler);

const PORT = process.env.PORT || 5000;

const server = app.listen(
  PORT,
  console.log(
    `Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold
  )
);

//Handle unhandled promise rejections
process.on("unhandledRejection", (err, promise) => {
  console.log(`Error: ${err.message}`.red);
  // Close server & exit process
  server.close(() => process.exit(1));
});

Screenshot of error message

Merry Christmas gurus and keep on coding!!!

Determine a prime number function

//could anyone explain to me the 2nd and 3rd statement in the for loop
//what is the 1st and 2nd i in the middle part and the last one (i = i + 6)

function prime(n) {
  if (n<=1) return false;
  if (n<=3) return true;

  if (n%2==0||n%3==0) return false
  for(let i=5;i*i<n; i=i+6) {  
    if (n%1==0||n%(i+2)==0)

    return false;
  }
  return true
}

How to parse redirect URL or the request sent to it by OAuth 2 in react-native, with expo-auth-session

I am trying to implement OAuth 2 with the expo-auth-session module.

My user is able to authenticate and is redirected to my backend web server, which is able to recieve the authentication code from the API provider. I was able to do so without using expo-auth-session package.

What I want now is to fire a callback function that prints the provider’s response (the one that is sent to my redirect uri) or at least the complete url (with get parameters) the response is sent to. From what I understand, expo-auth-session should allow me to do so.

Note : I cannot provide a custom scheme because the provider only allows http and https schemes. Regardless, when the user is redirected, the application should be able to parse the query parameters and to trigger a callback.

Here is my code :

import React, { useState } from 'react';
import * as WebBrowser from 'expo-web-browser';
import { makeRedirectUri, useAuthRequest } from 'expo-auth-session';
import { Button, Platform } from 'react-native';

WebBrowser.maybeCompleteAuthSession(); // useless on native

// Endpoint
const discovery = {
  authorizationEndpoint: 'https://provider.com/oauth/authorize',
  tokenEndpoint: 'http://192.168.1.8:8080/token', // <-- I'm not really sure exactly what this should be? My guess is my own backend should return a token to identify my users who authenticated with the API. At least that's what I would like to do.
};

const useProxy = Platform.select({ web: false, default: true }); // not using this right now

export default function App() {
  const [step, setStep] = useState('start'); // 
  const [request, response, promptAsync] = useAuthRequest(
    {
      ':region': 'eu',
      clientId: 'myClientId',
      scopes: ['wow.profile'],
      responseType: 'code',
      redirectUri: 'http://192.168.1.8:8080/login', // this is my backend's route where I retrieve the user's authentication code,
      // prompt: Prompt.None,
      state: 'someteststate', // yes I know this isn't good practice but this is just for testing.
      extraParams: { 'customProviderKey': 'value' }
    },
    discovery
  );

  React.useEffect(() => {
    if (response?.type === 'success') {
      const { code } = response.params;
      console.log(code);
    } else if (response) {
        console.log(response);
    } else {
      console.log("No response..."); // this fires when the component is loaded, before the user authenticates.
    }
  }, [response]);

  return (
    <Button
      disabled={!request}
      title="Login"
      onPress={() => {
        promptAsync({ useProxy });
        }}
    />
  );
}

I should mention this code is almost a copy of this guide : https://docs.expo.dev/guides/authentication/#dropbox

Note 2 : I’m at a point of my application where there are not much expo dependencies so I’m not closed to the idea of using libraries that would work on standalone (non-expo) apps. In that case I would need an in-app browser module that exposes functions to retrieve redirect and response parameters, and to trigger callbacks on page load… something like that.

” ParseError: Unexpected character ‘@’ ” when parsing css of 3rd-party library (UI-Material Preact)

this project has been given to us to extend by adding new functionality. I am still an undergrad student and have never developed a web app of this scale 🙂 and have never worked with the used technologies and node modules before.

I tried using this preact library in a stand-alone default preact app and it works just fine, but doesn’t when integrating it in our project.

I’m still a newbie but I guessed, according to this article, that babel configuration is causing the problem.

I’d be very grateful for any info about the used packages or if u could just point me in the right direction to debugging this problem.

Here is the function that bundles JavaScript source files:

module.exports = function createBundle(config, buildOpts) {
  fs.mkdirSync(config.path, { recursive: true });

  buildOpts = buildOpts || { watch: false };

  // Use a custom name for the "require" function that bundles use to export
  // and import modules from other bundles. This avoids conflicts with eg.
  // pages that use RequireJS.
  const externalRequireName = 'hypothesisRequire';

  const bundleOpts = {
    debug: true,

    // Browserify will try to detect and automatically provide
    // browser implementations of Node modules.
    //
    // This can bloat the bundle hugely if implementations for large
    // modules like 'Buffer' or 'crypto' are inadvertently pulled in.
    // Here we explicitly whitelist the builtins that can be used.
    //
    // In particular 'Buffer' is excluded from the list of automatically
    // detected variables.
    //
    // See node_modules/browserify/lib/builtins.js to find out which
    // modules provide the implementations of these.
    builtins: ['console', '_process', 'querystring'],
    externalRequireName,

    // Map of global variable names to functions returning _source code_ for
    // the values of those globals.
    insertGlobalVars: {
      // Workaround for Hammer.JS on pages that use RequireJS. Hammer doesn't
      // set `module.exports` if a global variable called `define` exists.
      define: () => 'undefined',

      // The Browserify polyfill for the `Buffer` global is large and
      // unnecessary, but can get pulled into the bundle by modules that can
      // optionally use it if present.
      Buffer: undefined,

      // Override the default stub for the `global` var which defaults to
      // the `global`, `self` and `window` globals in that order.
      //
      // This can break on web pages which provide their own definition of
      // `global` or `self` that is not an alias for `window`. See
      // https://github.com/hypothesis/h/issues/2723 and
      // https://github.com/hypothesis/client/issues/277
      global: function () {
        return 'window';
      },
    },
  };

  if (buildOpts.watch) {
    bundleOpts.cache = {};
    bundleOpts.packageCache = {};
  }

  // Specify modules that Browserify should not parse.
  // The 'noParse' array must contain full file paths,
  // not module names.
  bundleOpts.noParse = (config.noParse || []).map(function (id) {
    // If package.json specifies a custom entry point for the module for
    // use in the browser, resolve that.
    const packageConfig = require('../../package.json');
    if (packageConfig.browser && packageConfig.browser[id]) {
      return require.resolve('../../' + packageConfig.browser[id]);
    } else {
      return require.resolve(id);
    }
  });

  // Override the "prelude" script which Browserify adds at the start of
  // generated bundles to look for the custom require name set by previous bundles
  // on the page instead of the default "require".
  const defaultPreludePath = require.resolve('browser-pack/prelude');
  const prelude = fs
    .readFileSync(defaultPreludePath)
    .toString()
    .replace(
      /typeof require == "function" && require/g,
      `typeof ${externalRequireName} == "function" && ${externalRequireName};`
    );
  if (!prelude.includes(externalRequireName)) {
    throw new Error(
      'Failed to modify prelude to use custom name for "require" function'
    );
  }
  bundleOpts.prelude = prelude;

  const name = config.name;

  const bundleFileName = name + '.bundle.js';
  const bundlePath = config.path + '/' + bundleFileName;
  const sourcemapPath = bundlePath + '.map';

  const bundle = browserify([], bundleOpts);

  (config.require || []).forEach(function (req) {
    // When another bundle uses 'bundle.external(<module path>)',
    // the module path is rewritten relative to the
    // base directory and a '/' prefix is added, so
    // if the other bundle contains "require('./dir/module')",
    // then Browserify will generate "require('/dir/module')".
    //
    // In the bundle which provides './dir/module', we
    // therefore need to expose the module as '/dir/module'.
    if (req[0] === '.') {
      bundle.require(req, { expose: req.slice(1) });
    } else if (req[0] === '/') {
      // If the require path is absolute, the same rules as
      // above apply but the path needs to be relative to
      // the root of the repository
      const repoRootPath = path.join(__dirname, '../../');
      const relativePath = path.relative(
        path.resolve(repoRootPath),
        path.resolve(req)
      );
      bundle.require(req, { expose: '/' + relativePath });
    } else {
      // this is a package under node_modules/, no
      // rewriting required.
      bundle.require(req);
    }
  });

  bundle.add(config.entry || []);
  bundle.external(config.external || []);
  (config.transforms || []).forEach(function (transform) {
    if (transform === 'babel') {
      bundle.transform(babelify.configure({
        presets: ["es2015"]
      }));
    }
  });

  // Include or disable debugging checks in our code and dependencies by
  // replacing references to `process.env.NODE_ENV`.
  bundle.transform(
    envify({
      NODE_ENV: process.env.NODE_ENV || 'development',
    }),
    {
      // Ideally packages should configure this transform in their package.json
      // file if they need it, but not all of them do.
      global: true,
    }
  );
  

  if (config.minify) {
    bundle.transform({ global: true }, minifyStream);
  }

  function build() {
    const output = fs.createWriteStream(bundlePath);
    let stream = bundle.bundle();
    stream.on('error', function (err) {
      log('Build error', err.toString());
    });

    if (config.minify) {
      stream = stream.pipe(minifyStream());
    }

    stream = stream.pipe(exorcist(sourcemapPath)).pipe(output);
    return streamFinished(stream);
  }

  if (buildOpts.watch) {
    bundle.plugin(watchify);
    bundle.on('update', function (ids) {
      const start = Date.now();

      log('Source files changed', ids);
      build()
        .then(function () {
          log('Updated %s (%d ms)', bundleFileName, Date.now() - start);
        })
        .catch(function (err) {
          console.error('Building updated bundle failed:', err);
        });
    });
    build()
      .then(function () {
        log('Built ' + bundleFileName);
      })
      .catch(function (err) {
        console.error('Error building bundle:', err);
      });
    return waitForever();
  } else {
    return build();
  }
};

These are the dependencies in package.json in case it offers any help:

"dependencies": {
    "alert": "^5.0.10",
    "axios": "^0.21.1",
    "babel-preset-env": "^1.7.0",
    "express-fileupload": "^1.2.1",
    "express-rate-limit": "^5.2.6"
  },
  "devDependencies": {
    "@actions/core": "^1.2.6",
    "@babel/core": "^7.1.6",
    "@babel/preset-env": "^7.1.6",
    "@babel/preset-react": "^7.0.0",
    "@hypothesis/frontend-shared": "^1.4.0",
    "@octokit/rest": "^18.0.0",
    "@sentry/browser": "^6.0.2",
    "approx-string-match": "^1.1.0",
    "autoprefixer": "^10.0.1",
    "axe-core": "^4.0.0",
    "babel-plugin-inject-args": "^1.0.0",
    "babel-plugin-istanbul": "^6.0.0",
    "babel-plugin-mockable-imports": "^1.5.1",
    "babel-plugin-transform-async-to-promises": "^0.8.6",
    "babel-preset-es2015": "^7.0.0-beta.0",
    "babelify": "^10.0.0",
    "browserify": "^17.0.0",
    "browserify-versionify": "^1.0.6",
    "chai": "^4.1.2",
    "chance": "^1.0.13",
    "classnames": "^2.2.4",
    "codecov": "^3.1.0",
    "commander": "^7.0.0",
    "core-js": "^3.4.1",
    "cross-env": "^7.0.0",
    "diff": "^5.0.0",
    "dompurify": "^2.0.1",
    "enzyme": "^3.8.0",
    "enzyme-adapter-preact-pure": "^3.0.0",
    "escape-html": "^1.0.3",
    "escape-string-regexp": "^4.0.0",
    "eslint": "^7.3.1",
    "eslint-config-hypothesis": "^2.4.0",
    "eslint-plugin-jsx-a11y": "^6.2.3",
    "eslint-plugin-mocha": "^8.0.0",
    "eslint-plugin-react": "^7.12.4",
    "eslint-plugin-react-hooks": "^4.0.4",
    "exorcist": "^1.0.1",
    "express": "^4.14.1",
    "fancy-log": "^1.3.3",
    "fetch-mock": "9",
    "focus-visible": "^5.0.0",
    "gulp": "^4.0.0",
    "gulp-babel": "^8.0.0",
    "gulp-changed": "^4.0.0",
    "gulp-rename": "^2.0.0",
    "gulp-replace": "^1.0.0",
    "gulp-sourcemaps": "^3.0.0",
    "hammerjs": "^2.0.4",
    "karma": "^6.0.1",
    "karma-browserify": "^8.0.0",
    "karma-chai": "^0.1.0",
    "karma-chrome-launcher": "^3.1.0",
    "karma-coverage-istanbul-reporter": "^3.0.2",
    "karma-mocha": "^2.0.0",
    "karma-mocha-reporter": "^2.0.4",
    "karma-sinon": "^1.0.5",
    "katex": "^0.12.0",
    "lodash.debounce": "^4.0.3",
    "loose-envify": "^1.4.0",
    "mocha": "8.3.0",
    "mustache": "^4.0.1",
    "mustache-express": "^1.3.0",
    "npm-packlist": "^2.0.1",
    "postcss": "^8.0.3",
    "postcss-url": "^10.0.0",
    "preact": "^10.4.0",
    "preact-cli": "^3.0.0",
    "preact-material-components": "^1.6.1",
    "prettier": "2.2.1",
    "puppeteer": "^8.0.0",
    "query-string": "^3.0.1",
    "redux": "^4.0.1",
    "redux-thunk": "^2.1.0",
    "reselect": "^4.0.0",
    "retry": "^0.12.0",
    "sass": "^1.23.0",
    "scroll-into-view": "^1.8.2",
    "shallowequal": "^1.1.0",
    "showdown": "^1.6.4",
    "sinon": "^9.0.0",
    "stringify": "^5.1.0",
    "terser": "^5.0.0",
    "through2": "^4.0.1",
    "tiny-emitter": "^2.0.2",
    "typescript": "^4.0.2",
    "vinyl": "^2.2.0",
    "watchify": "^3.7.0",
    "wrap-text": "^1.0.7"
  },

Thanks in advance 🙂

Replace variable of WordPress shortcode based on select box?

Is it possible to do this without Ajax, solely with vanilla JS and PHP?

What I am trying to do is:

  • Return the shortcode in PHP (easy)
  • Show it on the page (easy)
  • Allow users to select a text on the front-end (HTML is easy, but how do I send this as a variable?)
  • Change the shortcode variable with the chosen text on the front-end and load it dynamically on the page.

My question is: what options do I have? Is it solely Ajax or can I do this with PHP and JS-only?

function place_function() {
   
     return '[myshortcode place="new york"]';
}

Angular: Scoring a checkbox or Radio Button. Clearing the answer if answer is changed

I am having problems with the scoring of my quiz.Currently i can add up the number of right and wrong answers upon submit of each question.However, when the person tries to go back and change his answer, the new score is added on top of the old one.That means i can have 2 Wrong answers for each question, which leads to a wrong answer. I am a beginner. Please help.

Quiz

Next.JS custom form validation not working – ReactJS

I have a contact page, and I am trying to validate the form. When page is refreshed and I click on submit button then only the last element’s error is generated, it should generate error for every input according to validation.
Screenshot of form issue
Form validation is working perfect with onChange event. But it doesn’t work fine when page is refreshed and I click on submit button without putting values to inputs.
Here is my code:

import { useState } from "react";

function ContactForm() {

    const [fields, setFields] = useState({});
    const [errors, setErrors] = useState({});
    const [formValid, setFormValid] = useState(false);

    async function handleOnSubmit(e) {
        e.preventDefault();

        console.log('fields', fields);
        console.log('errors', errors);
        console.log('formValid', formValid);

        const formData = {};
        [...e.currentTarget.elements].map((field) => {
            if (!field.name) return false;
            checkValidation([field.name], field.value);
            setFields({...fields, [field.name]: field.value});
        });

        if (formValid === false) return false;

        try {
            const response = await fetch('/api/mail', {
                                method: 'post',
                                body: JSON.stringify(formData)
                            });
            const body = await response.json();
            console.log(body);
        } catch (error) {
            console.log(error);
        }

        console.log(formData);
    }

    function handleValidation(e) {
        const name = e.target.name;
        const value = e.target.value;
        checkValidation(name, value);
    }

    function checkValidation(name, value) {
        if (value === "") {
            delete fields[name];
            setErrors({...errors, [name]: 'Required'});
            setFormValid(false);
            return false;
        }

        delete errors[name];
        setFields({...fields, [name]: value});
        setFormValid(true);
        // Special validation for email
        emailValidation(name, value);

        console.log('fields on validaton', fields);
        console.log('errors on validation', errors);
    }

    // Email Validation
    function emailValidation(name, value) {
        const emailRegex = new RegExp(/[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,15}/g);
        if ((name == 'email') && (emailRegex.test(value) === false)) {
            delete fields[name];
            setErrors({...errors, [name]: 'Email is not validate'});
            setFormValid(false);
        }
    }

    return (
        <div className="mt-5 mt-md-0">
            <h1 className="section-title h1-responsive text-center mb-4">
                <span>
                    Contact Us
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 456.99 38"><defs><style dangerouslySetInnerHTML={{__html: ".cls-1{fill:#cb0a34;}" }} /></defs><title>latest from out videos</title><g id="Layer_2" data-name="Layer 2"><g id="Layer_1-2" data-name="Layer 1"><path className="cls-1" d="M456.28,8.29a4.6,4.6,0,0,0,.29-.59c0-.11.08-.21.11-.31a4.56,4.56,0,0,0,.21-.72l0-.21A6.11,6.11,0,0,0,457,5.6h0a5.5,5.5,0,1,0-9.24,4C422.6,9.89,288,9.52,281.13,9.52h-31c-7.86,0-15.13,2.18-21.14,7.26a30.14,30.14,0,0,0-8.72-5.25c-4.68-1.82-9.42-2-14.32-2H9.24A5.5,5.5,0,1,0,0,5.5v0c0,.05,0,.09,0,.14a3.4,3.4,0,0,0,0,.45c0,.12,0,.23,0,.35l.06.3A1.82,1.82,0,0,0,.22,7,5.48,5.48,0,0,0,4.5,10.9a5.13,5.13,0,0,0,1.12.16c.85,0,1.7,0,2.54,0H209.44a28.85,28.85,0,0,1,19,7.26,28.31,28.31,0,0,0-6.38,9.13L229,38.29,236,27.45h0a28.11,28.11,0,0,0-6.38-9.12A28.8,28.8,0,0,1,241.09,12c4-1.09,8-1,12.14-1H451l.54,0a5.47,5.47,0,0,0,3.21-1l.07,0s0,0,.05-.05a4.53,4.53,0,0,0,.62-.54l.24-.26a6.41,6.41,0,0,0,.39-.52C456.15,8.52,456.21,8.4,456.28,8.29Z" /></g></g></svg>
                </span>
            </h1>
            <form className="contact_form" method="post" onSubmit={handleOnSubmit}>
                <div className="response-status"></div>
                <div className="form-group row">
                    <div className="col-md-6 mb-2">
                        <label className="mb-1">Name <span className="text-danger">*</span></label>
                        <input
                            type="text"
                            name="name"
                            className={`form-control ${errors.name ? 'is-invalid' : ''}`}
                            onChange={handleValidation}
                        />
                        {errors.name && <span className="text-danger">{errors.name}</span>}
                    </div>
                    <div className="col-md-6 mb-2">
                        <label className="mb-1">Email <span className="text-danger">*</span></label>
                        <input
                            type="text"
                            name="email"
                            className={`form-control ${errors.email ? 'is-invalid' : ''}`}
                            onChange={handleValidation}
                        />
                        {errors.email && <span className="text-danger">{errors.email}</span>}
                    </div>
                    <div className="col-md-12 mb-2">
                        <label className="mb-1">Subject:</label>
                        <input type="text" name="subject" className="form-control" />
                    </div>
                    <div className="col-md-12 mb-3">
                        <label className="mb-1">Message <span className="text-danger">*</span></label>
                        <textarea
                            name="message"
                            className={`form-control ${errors.message ? 'is-invalid' : ''}`}
                            rows="5"
                            onChange={handleValidation}
                        ></textarea>
                        {errors.message && <span className="text-danger">{errors.message}</span>}
                    </div>
                    <div className="col-md-12">
                        <button type="submit" className="btn btn-primary btn-block rounded waves-effect waves-light">Send Message</button>
                    </div>
                </div>
            </form>
        </div>
    )
}

export default ContactForm

I don’t know why it is not working fine. Please check the code. I can’t find the issue in my code, I am stuck.

Decreasing the complexity of the JS algorithm for creating slots based on days of the week

Trying to generate slots in future based on availableTimes, slots are nothing but they have start time and end time based on slotSize and startTime

Example data:

availableTimes: 
{
  TUESDAY: [{ dayOfTheWeek: "TUESDAY", start: 8, end: 10 }],
},
daysInFuture: 1,
timeZone: "Australia/Melbourne",
slotSizeInMinutes: 60,
timeStamp: 1640041590364

Based on this availableTime Data and considering current date is

2021-12-21T08:00:00.000+11:00

it should return

[
    {
      ref: "2021-12-21T08:00:00.000+11:00",
      startTime: "2021-12-21T08:00:00.000+11:00",
      endTime: "2021-12-21T09:00:00.000+11:00",
      available: true,
    },
    {
      ref: "2021-12-21T09:00:00.000+11:00",
      startTime: "2021-12-21T09:00:00.000+11:00",
      endTime: "2021-12-21T10:00:00.000+11:00",
      available: true,
    },
  ]

which is working as expected, I just want to decrease the complexity of the function.

function generateTimeSlots(
  availableTimes: {
    [x: string]: MenuAvailability[];
  },
  daysInFuture: number,
  timeZone: string,
  slotSizeInMinutes: number,
  timeStamp: number
): orders.TimeSlot[] {
  const timeSlots = [];

  for (let j = 0; j <= daysInFuture; j++) {
    let currentDate = DateTime.fromMillis(timeStamp)
      .setZone(timeZone)
      .plus({ days: j });

    const currentDay = currentDate.weekdayLong.toUpperCase() as DayOfTheWeek;
    const slotsForTheDay = availableTimes[currentDay] ?? [];

    for (let i = 0; i < slotsForTheDay.length; i++) {
      const startHour = slotsForTheDay[i].start;
      const endHour = slotsForTheDay[i].end;

      const numOfSlots = ((endHour - startHour) * 60) / slotSizeInMinutes;

      const addMinutes = (date: DateTime, minutes: number) => {
        return DateTime.fromISO(date.toISO()).plus({ minutes: minutes });
      };

      currentDate = currentDate.set({
        hour: startHour,
        minute: 0,
        second: 0,
        millisecond: 0,
      });

      for (let i = 0; i < numOfSlots; i++) {
        timeSlots.push({
          ref: currentDate.toISO(),
          startTime: currentDate.toISO(),
          endTime: addMinutes(currentDate, slotSizeInMinutes).toISO(),
          available: true,
        });
        currentDate = addMinutes(currentDate, slotSizeInMinutes);
      }
    }
  }

  return timeSlots;
}

Gradually opening sections addEventListener input

I have an accordion. The first section is open by default, the others are closed, after I fill the first one opens the next, the filled section is closed. I use addEventListener (" input "() => to dynamically read the results. The problem is that when I fill the second section and want to go to section 3, section 2 is closed and then opened.

The problem is listening to addEventListener (" input "() => since it listens to all changes. But the fact is that after the second section is closed, the values in it do not change in any way.

How to solve this problem? I need to consistently open the sections, the filled ones are closed.

window.document.addEventListener("input", () => {
  //check values
  let agesValues =
    age &&
    age.value !== age.value.defaultValue &&
    age.value !== null &&
    age.value !== "";

  if (
    (agesValues === true && male.checked) ||
    (agesValues === true && female.checked)
  ) {
    let inpush = () => {
     
      //show first section result
      blockresult1.classList.add("visible");
      //show second section inputs
      sectondSection.classList.remove("collapse");
    };
    setTimeout(inpush, 2000);
  }
  if () {
  
    if () {
    
      //show secons section result
      blockresult2.classList.add("visible");
      //close the section when it is full
        sectondSection.classList.add("collapse");
     
    }
  }
  if (
 my check
  ) {
  
    ) {
      let inpush = () => {
        
        changeButton3.classList.add("visible");
    
        thirdSection.classList.add("collapse");
      
        blockresult3.classList.add("visible");

      my actions
      
  
      };
      setTimeout(inpush, 2000);
    }
  }
.visible {
  display: block;
}
.collapse {
  display: none;
}
<form class="stepTwo-profile" id="formStepTwo">
    <p class="stepTwo-profile-title">Демография</p>
    <div class="stepTwo-profile-item">
      <a href="#" class="stepTwo-profile-item-change1">Изменить</a>
      <div class="stepTwo-profile-result1">
        <p class="stepTwo-profile-result1-text">
          Возраст пациента:<span
            class="stepTwo-profile-result1-text-sub"
            id="resultAge"
          ></span>
        </p>
        <p class="stepTwo-profile-result1-text">
          Пол:<span
            class="stepTwo-profile-result1-text-sub"
            id="resultGender"
          ></span>
        </p>
      </div>
      <div id="firstsection">
        <label for="age"
          >Возраст пациента<input
            type="number"
            class="stepTwo-profile-item-textAge"
            name="age"
            min="0"
            max="80"
            maxlength="2"
            id="age"
        /></label>
        <p class="stepTwo-profile-item-smTitle">Пол</p>
        <label for="male">
          <input type="radio" name="gender" id="male" value="male" />Мужской
          <span class="stepTwo-profile-item-radionbtn"></span
        ></label>

        <label for="female">
          <input type="radio" name="gender" id="female" value="female" />Женский
          <span class="stepTwo-profile-item-radionbtn"></span>
        </label>
      </div>
    </div>
    <p class="stepTwo-profile-title">Статус пациента и заболевания</p>
    <div class="stepTwo-profile-item">
      <a href="#" class="stepTwo-profile-item-change2">Изменить</a>
      <div class="stepTwo-profile-result2">
        <p class="stepTwo-profile-result2-text">
          Предшествующая терапия:<span
            class="stepTwo-profile-result1-text-sub"
            id="trueTerapy"
          ></span>
        </p>
        <p class="stepTwo-profile-result2-text">
          Общее состояние и коморбидность:<span
            class="stepTwo-profile-result1-text-sub"
            id="OverStatus"
          ></span>
        </p>
      </div>
      <div id="sectondSection">
        <p class="stepTwo-profile-item-smTitle">Предшествующая терапия</p>

        <label for="prev-terapy1">
          <input type="radio" name="prev-terapy" id="prev-terapy1" />Нет spa
          <span class="stepTwo-profile-item-radionbtn"></span>
        </label>
        <label for="prev-terapy2">
          <input type="radio" name="prev-terapy" id="prev-terapy2" />Радикальное
          лечение завершено <span class="stepTwo-profile-item-radionbtn"></span>
        </label>
        <label for="prev-terapy3">
          <input type="radio" name="prev-terapy" id="prev-terapy3" />Одна линия
          терапии <span class="stepTwo-profile-item-radionbtn"> </span
        ></label>
        <label for="prev-terapy4">
          <input type="radio" name="prev-terapy" id="prev-terapy4" />Две или
          более линии терапии
          <span class="stepTwo-profile-item-radionbtn"></span>
        </label>

        <p class="stepTwo-profile-item-smTitle smTitleSecondsChilds">
          Общее состояние и коморбидность
        </p>
        <label for="status1">
          <input type="radio" name="status" id="status1" />ECOG 0-1
          <span class="stepTwo-profile-item-radionbtn"></span
        ></label>
        <label for="status2">
          <input type="radio" name="status" id="status2" />ECOG 2
          <span class="stepTwo-profile-item-radionbtn"></span
        ></label>
        <label for="status3">
          <input type="radio" name="status" id="status3" />ECOG 3-4 | высокая
          коморбидность
          <span class="stepTwo-profile-item-radionbtn"></span>
        </label>
      </div>
    </div>
    </form>

It should be like this
It should be like this

What do I get after a couple of seconds

What do I get after a couple of seconds

enter image description here

node js express use app.get with created name to redirect to it

I have code below. We post room name with ajax to url /room-api

function getCreatedRoomName(x){

  $.ajax({
    type: "POST",
    url: "/room-api",
    data: { roomname: x },
    success: function(data) {
    },
    error: function(jqXHR, textStatus, err) {
    alert('text status '+textStatus+', err '+err)
    }
    });

  return x;
}

app.js

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));


var room_name;

app.post('/room-api', isLoggedIn, function(req, res){
  room_name = req.body.roomname;
  console.log(room_name);
});

Then we receive that data with app.post as you can see above. How can I create a new app.get with created name? I tried this.

app.post('/room-api', isLoggedIn, function(req, res){
  room_name = req.body.roomname;

  app.get(`/${room_name}`, isLoggedIn, function(req, res){
      res.redirect(`/${room_name}`);
  });

  console.log(room_name);
});

But it doesn’t work.