Access archived content from Nature Education website

I am trying to access a website that has been archived and is no longer updated.

This website is partially accessible. Yet I am only able to access the main pages but not the subsections.

For example, this page (Understanding Communication > Taking the medium into account) is accessible:

https://www.nature.com/scitable/ebooks/english-communication-for-scientists-14053993/118519407/

But I cannot access this page (Understanding Communication > Showing respect for your audience):

https://www.nature.com/scitable/ebooks/english-communication-for-scientists-14053993/118519407/#2

I contacted the customer service of Nature. But they are not willing to help.

As some content is still online, I am wondering if I could still access all the content (maybe by using other javascript calls — I am very naive about this).

how to make var return 0.00 instead of NaN?

Im working on a price calculator at the moment but in the var proapp2 it will show NaN when the pro app Benutzer slider is 0 how can i make it show 0.00 instead of NaN? i tried if (isNaN(proapp2)) proapp2 = 0.00; but it didnt work?What am i doing wrong?Also i want it to return 0.00 instead of 0.i tried var proapp2 = proapp2 | 0;
as well.

   
const btncalc = document.querySelector('.calcit');
const summetext = document.querySelector('.summe');
const backend = document.querySelector('.backenduser');
const update = document.querySelectorAll('.update');
const backendstk = document.querySelector('.backendanzahl')
const appstk = document.querySelector('.appanzahl')
const preisproapp = document.querySelector('.proapp')
const preisprobackend = document.querySelector('.probackend')
const jährlich = document.querySelector('.rabatt')

update.forEach(input => {
  input.addEventListener('input', function() {
   calcSum();
  })
});
//funktion damit der Slider sich beim eingeben vom input field bewegt
function updateAppUser(val, inputtype) {
  if(inputtype == 'appslider'){
    document.getElementById('AppInput').value=val;
  }
  if(inputtype == 'appinput'){
    document.getElementById('appuserSlider').value=val;
  }
  calcSum();
}
function updateBackendUser(val, inputtype) {
  if(inputtype == 'backendslider'){
    document.getElementById('BackendInput').value=val;
  }
  if(inputtype == 'backendinput'){
    document.getElementById('backendSlider').value=val;
  }
  calcSum();
}


//Rechnung für die Anzahl von Backend und App-Benutzern
function calcSum(){
  var backendanzahl = document.getElementsByClassName("backenduser")[0].value;
  var appanzahl = document.getElementsByClassName("appuser")[0].value;
//Preisstaffelung für app und backend  
  apppreis = 7.5; 
  if(appanzahl < 11){
    apppreis = 7.5;
  }else if(appanzahl < 26){
    apppreis = 7;
  }else if(appanzahl < 51){
    apppreis = 6.50;
  }else if(appanzahl < 76){
    apppreis = 6;
  }else if(appanzahl > 76){
    apppreis = 5.5;
  }

  var mylist = document.getElementById("myList");
  var backendtype = mylist.options[mylist.selectedIndex].value;
  backendpreis = 35;
  if(backendtype == "ZR"){
    if(backendanzahl < 5 ){
      backendpreis = 35;
    }else if(backendanzahl < 11){
      backendpreis = 32.50;
    }else if(backendanzahl < 21){
      backendpreis = 30 ;
    }
  }else{
    if(backendanzahl < 6){
      backendpreis = 20;
    }else if(backendanzahl < 11){
      backendpreis = 18;
    }else if(backendanzahl < 21){
      backendpreis = 16 ;
    }
  }
  if (isNaN(proapp2)) proapp2 = 0.00;
  
  var mytext = ((backendanzahl * backendpreis + +appanzahl * apppreis) * 1).toFixed(2);
  summetext.textContent = mytext;
  
  var backendpreissumme =(backendanzahl * backendpreis).toFixed(2);
  backendstk.textContent = backendpreissumme;
 
  var apppreissumme =(appanzahl * apppreis).toFixed(2);
  appstk.textContent = apppreissumme;
  
  var probackend2 =((backendpreis*backendanzahl)/(backendanzahl)).toFixed(2);
  preisprobackend.textContent = probackend2;
  
  var proapp2 =((apppreis*appanzahl)/(appanzahl)).toFixed(2);
  preisproapp.textContent = proapp2;

  var jährlicherrabatt = ((backendanzahl * backendpreis + +appanzahl * apppreis) * 0.9).toFixed(2);
  jährlich.textContent = jährlicherrabatt;
  
<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="styles.css">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  </head>
  <body>
    <div class="grid-container">
      <div class="grid-item">
        <header>Preiskalkulator</header>
        <div class="slidecontainer">
          App-Benutzer: <br>
          <input id="appuserSlider" value="0" onchange="updateAppUser(this.value);" type="range" min="0" max="100" oninput="this.value = this.value > 100 ? 100 : Math.abs(this.value); updateAppUser(this.value, 'appslider');" class='appuser update'></input>
          <input type="text" id="AppInput" value="0" placeholder="1-100" oninput="this.value = this.value > 100 ? 100 : Math.abs(this.value); updateAppUser(this.value, 'appinput');"><br>
          Backendbenutzer: <br>
          <input id="backendSlider" value="1" onchange="updateBackendUser(this.value);" type="range" min="1" max="15" oninput="this.value = this.value > 15 ? 15 : Math.abs(this.value); updateBackendUser(this.value, 'backendslider'); " class='backenduser update'></input>
          <input type="text" id="BackendInput" value="1" placeholder="1-15" oninput="this.value = this.value > 15 ? 15 : Math.abs(this.value,); updateBackendUser(this.value, 'backendinput');"><br>
        </div>
        <b> Bürosoftware wählen </b>
        <select id = "myList" onchange = "calcSum()" >
          <option value="Z">Zeiterfassung</option>
          <option value="ZR"> Zeiterfassung + Rechnungswesen</option>
        </select>
      </div>
      <div class="grid-item" style="width: 250px">
        <table style="width:100%;text-align: right;">
          <tr>
            <td style="width: 138px" >App-Benutzer<br> pro <span class="proapp" style="color:grey">7,50</span>€</td>
            <td style="width: 62px" class='appanzahl'>75,00€</td>
          </tr>
          <tr>
            <td>Backend-Benutzer<br >pro <span class='probackend'>35,00</span>€</td>
            <td class='backendanzahl'>175,00€</td>
          </tr>
          <tr><td colspan="2"><hr></td></tr>
          <tr>
          <td >Gesamtpreis:<br>(zzgl. MwSt)</td>
            <td class='summe'>75,00€</td>
          </tr>
          <tr>
            <td >Jährlich<br></td>
            <td class='rabatt'></td>
          </tr>
        </table>
      </div>
      <script src="./app.js"></script>
  </body>
</html>
  

how pass array and values in ajax data to controller in java script

var Batch_value = document.getElementById("B_ID").innerText;  
type: 'POST',
            url: "/Upload/InsertInfo",
            data:JSON.stringify({ jsonArray, B_value}),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {},
            failure: function (response) {});
            },

// how I can pass one object value and one array to the controller

RTK Query Pattern for fetching data with query arguments

I have an application where multiple components are fetching data like below and is using the data for some rendering.

const {data} = useGetUserQuery({shippingAddressId: 123});

I’m trying to figure out what is the normal RTK query pattern if I wanted to call useGetUserQuery with a new shippingAddressId and have all the components consuming this hook rerender?

Since RTK Query uses the query parameters as cache keys, the data doesn’t update since the shippingAddressId is hardcoded.

I’m currently getting around this by dispatching an action to the redux store which updates a params object with say shippingAddressId and using that as my query argument in the useGetUserQuery({...params}) hook.

By dispatching an action, all my components that are consuming the useGetUserQuery hook gets updated.

Is this an anti-pattern?

Thank you and I look forward to any recommendations.

How to show PHP validation error message that is received in Ajax response in a HTML form

I am receiving valid json response when the form is not submitted (when the validation fails)
I can print it in console. I am struggling to show that validation error message to the HTML form under or next to the proper field.

my form

<form action="" method="post" name="contact-me" id="profile-update" class="requires-validation">
    <div class="d-flex flex-row align-items-center mb-4">  
        <i class="fas fa-key fa-lg me-3 fa-fw"></i>
        <div class="d-flex form-floating mb-0 flex-fill">    
            <input name="name" type="text" class="form-control name" placeholder="Type your name" >
            <label for="name" class="form-label">Your Name</label>
            <div class="nameerror">Name field is valid!</div>
        </div>
    </div>    

    <div class="d-flex flex-row align-items-center mb-4">  
        <i class="fas fa-key fa-lg me-3 fa-fw"></i>
        <div class="d-flex form-floating mb-0 flex-fill">   
            <input name="email"  type="email" class="form-control" placeholder="Type a valid email" >
            <label for="email" class="form-label">Your Email</label>
            <div class="emailerror">Name field is valid!</div>
        </div>    
    </div>

    <div class="d-flex justify-content-center mx-4 mb-3 mb-lg-4">
        <button type="submit" class="btn btn-primary btn-lg" id="submit">Send message!</button>
    </div>
    <div id="nds_form_feedback"></div>
</form>

So I want to show the name validation error message in <div class="nameerror">Name field is valid!</div> and email validation error message in <div class="emailerror">Name field is valid!</div>

my validation

<?php 
   function prfl_update_validation_func(){
    $errors = array();
    $response = array();

    $yourname=$_POST['yourname']; 
    $yourname=$_POST['email']; 

    if ((empty($_POST['yourname'])) ) {
        $errors['yourname'] = "Please enter your name"; 
    } 

    if ((!empty($_POST['yourname'])) && (!preg_match("/^[a-zA-Z-' ]*$/",($_POST['yourname'])))) {
        $errors['yourname'] = "Special characters or spaces are not allowed in the username";    
    }
    
    if ((empty($_POST['email'])) ) {
        $errors['email'] = "Please enter your email";    
    } 

    $response['errors'] = $errors;

     if($errors) {

        $response['success'] = false;
        $response['message'] = "Fail";

    } else {

        $reponse['success'] = true;
        $response['message'] = "<div class='alert alert-success'>Article added</div>";
    }

    echo json_encode($response);
    wp_die();
  }

So all my form validation errors are in $response['errors'] = $errors; right?

now, Ajax part. please read the commented lines as well

<script type="text/javascript">
    jQuery(document).on('click', '#submit', function(e){
        e.preventDefault();
        var fd = new FormData();

        fd.append('action', 'prfl_update_validation_func');   

        jQuery.ajax({
            type: 'POST',
            url: ajax_url,
            data: fd,
            contentType: false, //because I have a file upload feild as well
            processData: false, //because I have a file upload feild as well
            headers: {Accept : "application/json;charset=utf-8"},
            debug:true,
            success: function(response) {
                if(response.type == "success") {
                   jQuery("#nds_form_feedback").html('Sucessfully Sent'); // if the form passes the validation this works fine
                }
                else {
                    alert("Not Uploaded");
                   
                    jQuery("#nds_form_feedback").html('boooooooooooo'); // this replace the div #nds_form_feedback correctly if there is a validation error
                    
                    jQuery("#nds_form_feedback").html("<ul><li>"+errors.email+"</li></ul>"); // this says 'errors' is not defined

                    console.log(response);

                }
             }
       
    });
});

</script>

what I want here is showing the correct validation error message under/next to it’s input fields.

jQuery("#nds_form_feedback").html("<ul><li>"+errors.email+"</li></ul>"); this needs to be replaced with correct classes and with correct array values.

[EDIT]
json response I am getting in console

{
  "errors": {
    "yourname": "Please enter your name",
    "email": "Please enter your email"
  },
  "success": false,
  "message": "Fail"
}

Please help.

Possible Unhandled Promise Rejection (id: 0):

I need some tips about this error. I think the code might need a bunch of ‘try’ and ‘catch’ functions? I am new to this and I don’t know how to properly implement them.

Question: should the audio recorder record audio even with this warning happening?( this code is meant to integrate an audio recorder: Audio recorder npm package link )

Btw I am running the latest version of react native, I also only wrote code inside App.js (besides giving android permisions and completing the post-installation process) since in the latest version of react the linking of packages becomes Auto-Link which means the linking happens on installing a package (Source: https://reactnative.dev/blog/2022/06/21/version-069 )

App.js :

import React, {Component} from 'react';
import AudioRecorderPlayer from 'react-native-audio-recorder-player';

import {
  StyleSheet,
  View,
  TouchableOpacity,
} from 'react-native';

const App = () => {

  const audioRecorderPlayer = new AudioRecorderPlayer();

  const onStartRecord = async () => {
  const result = await this.audioRecorderPlayer.startRecorder();
  this.audioRecorderPlayer.addRecordBackListener((e) => {
    this.setState({
      recordSecs: e.currentPosition,
      recordTime: this.audioRecorderPlayer.mmssss(
        Math.floor(e.currentPosition),
      ),
    });
    return;
  });
  console.log(result);
};

const onStopRecord = async () => {
  const result = await this.audioRecorderPlayer.stopRecorder();
  this.audioRecorderPlayer.removeRecordBackListener();
  this.setState({
    recordSecs: 0,
  });
  console.log(result);
};

const onStartPlay = async () => {
  console.log('onStartPlay');
  const msg = await this.audioRecorderPlayer.startPlayer();
  console.log(msg);
  this.audioRecorderPlayer.addPlayBackListener((e) => {
    this.setState({
      currentPositionSec: e.currentPosition,
      currentDurationSec: e.duration,
      playTime: this.audioRecorderPlayer.mmssss(Math.floor(e.currentPosition)),
      duration: this.audioRecorderPlayer.mmssss(Math.floor(e.duration)),
    });
    return;
  });
};

const onPausePlay = async () => {
  await this.audioRecorderPlayer.pausePlayer();
};

const onStopPlay = async () => {
  console.log('onStopPlay');
  this.audioRecorderPlayer.stopPlayer();
  this.audioRecorderPlayer.removePlayBackListener();
};

  return (
  <View>
    <View style={{backgroundColor:'black',alignSelf:'center',marginTop:'3%'}}>
      <TouchableOpacity onPress={onStartRecord}>
        <Text style={styles.twhite}>Start Record</Text>
      </TouchableOpacity>
    </View>
    <View style={{backgroundColor:'black',alignSelf:'center',marginTop:'3%'}}>
    <TouchableOpacity onPress={onStopRecord}>
        <Text style={styles.twhite}>Stop Record</Text>
      </TouchableOpacity>
    </View>
    <View style={{backgroundColor:'black',alignSelf:'center',marginTop:'3%'}}>
    <TouchableOpacity onPress={onStartPlay}>
        <Text style={styles.twhite}>Start Play</Text>
      </TouchableOpacity>
    </View>
    <View style={{backgroundColor:'black',alignSelf:'center',marginTop:'3%'}}>
    <TouchableOpacity onPress={onPausePlay}>
        <Text style={styles.twhite}>Pause Play</Text>
      </TouchableOpacity>
    </View>
    <View style={{backgroundColor:'black',alignSelf:'center',marginTop:'3%'}}>
    <TouchableOpacity onPress={onStopPlay}>
        <Text style={styles.twhite}>Stop Play</Text>
      </TouchableOpacity>
    </View>
  </View>
  );
};

const styles = StyleSheet.create({
  twhite: {
    color:'white',
    fontSize:18,
  },
});

export default App;

“TypeError: map is undefined”

I was copying code from this solution: Is there a way to use leaflet.heat in react? and I’m getting an error

TypeError: map is undefined

enter image description here
in the getLocationCity function

export const getLocationCity = async (params) => {
  try {
    const body = DataCustom(params);
    const result = await instanceArcgis.post(
      "/rest/HomeLocation/11/query",
      body,
    );
    return await result?.data;
  }

I’m sure it’s a var or placement order issue, but I tried various options and it still doesn’t work. And it outputs results from the API but no Heatmap color comes out just ‘Marker’
enter image description here
Full JS code:

import React, { useEffect, useState, useRef } from "react";
import { GeoJSON } from "react-leaflet";
import { useRecoilValue, useSetRecoilState } from "recoil";
import HeatmapOverlay from "leaflet-heatmap";
import { arcgisToken } from "../recoil";
import { mapBounds, loadingMap } from "../state";
import { getLocationCity } from "../data/arcgis";
import "leaflet.heat";

export default function HSales() {
    const [data, setData] = useState();
    const setIsLoading = useSetRecoilState(loadingMap);
    const bounds = useRecoilValue(mapBounds);
    const tokenArcgis = useRecoilValue(arcgisToken);
    const geoJsonLayer = useRef(null);

    useEffect(() => {
        const fetchDataSpeedtestKel = () => {
            const body = {
                returnGeometry: true,
                rollbackOnFailure: true,
                geometry: JSON.stringify({
                    xmin: bounds.west,
                    ymin: bounds.south,
                    xmax: bounds.east,
                    ymax: bounds.north,
                    spatialReference: { wkid: 4326 },
                }),
                geometryType: "esriGeometryEnvelope",
                token: tokenArcgis,
            };

            setIsLoading(true);
            getLocationCity(body)
                .then((response) => {
                    const array = [];
                    response.features.forEach((element) => {
                        array.push({
                            type: "Feature",
                            properties: element["attributes"],
                            geometry: {
                                type: "Point",
                                coordinates: [
                                    element["geometry"]["x"],
                                    element["geometry"]["y"],
                                ],
                            },
                        });
                    });

                    const FeatureCollection = {
                        type: "FeatureCollection",
                        features: array,
                    };

                    if (geoJsonLayer.current) {
                        geoJsonLayer.current.clearLayers().addData(FeatureCollection);
                    }

                    const points = response.features
                        ? response.features.map((element) => {
                            return [
                                element["geometry"]["x"],
                                element["geometry"]["y"]
                            ];
                        })
                        : [];


                    setData(FeatureCollection);
                    L.heatLayer(getHeatmapChurn).addTo(data);
                })
                .catch((err) => console.log(err))
                .finally(() => setIsLoading(false));
        };

        fetchDataSpeedtestKel();
    }, [bounds, setIsLoading, tokenArcgis]);

    if (data) {
        return (
            <>
                <GeoJSON
                    ref={geoJsonLayer}
                    data={data}
                />
            </>
        );
    }
}

Thank you so much! Jim

Javascript library for password score

I implemented a password strength bar in react using zxcvbn and a custom score checking how many categories are satisfied. As zxcvbn is a little old, I am searching for an alternative. Do you have any recommendation? It would be nice to haves if it can support more languages than English, or can consider the number of matched categories, so I don’t need my custom function.

Javascript disabled button does not gets enabled when the form is completed

I have a form and I wanted to disable the submit button unless the required fields are filled.

So I added this:

$('#submitBtn').attr('disabled', true);

if ($('#inputMobile').val() != '' && $('#inputEmail').val() != '' && $('#inputPassword').val() != '' && $('#inputPasswordConfirmation').val() != '') {
      $('#submitBtn').attr('disabled', false);
}

Now it works fine and disable the submit button when the page loads but when I fill in the form fields, it does not enable the button however I tried setting the disabled attr to false.

So what’s going wrong here? How can I solve this issue?

anyone can fix this please Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’) at app.js:26:32 [duplicate]

const poll = {
question: ‘What is your favourite programming language ?’,
options: [‘0: JavaScript’,’1: Python’,’2:Rust’,’3:C++’],

//get answer
answers: new Array(4).fill(0),
registerNewAnswer (){
  const answer= Number(
    prompt(
    `${this.question}n${this.options.join('n')}
    n(write option number)`
    )
    );
console.log(answer);

//register answer

   typeof answer ==='number' && 
   answer < this.answers.length && 
   this.answers[answer]++;

},

};

document.querySelector(‘.bttn’).addEventListener(‘click’,poll.registerNewAnswer.bind(poll));

Publishing a npm package of shareable components for react js application

I want to build a npm package so I can share my components across the react application inside our organisation.

Here are the following doubts/questions I have:

  1. My components are using react-bootstrap and other third party libraries. Should I include in it as dependencies in package.json of package?
  2. Suppose I have added them as dependencies in package.json but My application still uses that packages too, Isn’t there will be duplication of the packages which results in bigger bundle size? What is the correct way to do that?
  3. What are the other solution to reduce the application bundle size, Mention the package dependencies as Peer dependencies?

Thanks in Advance

javascript null return asp.net

Blockquote jss.js

const dropArea = document.querySelector(".drag-area"),
dragText = dropArea.querySelector("header"),
button = dropArea.querySelector("button"),
input = dropArea.querySelector("input");
button.onclick = () => {
    input.click();
}

 

input.addEventListener("change", function () {
    files = this.files[0];   

 

dropArea.classList.add("active");

});


var myVideos = [];

window.URL = window.URL || window.webkitURL;

document.getElementById('fileUp').onchange = setFileInfo;

function setFileInfo() {


    let fileType = files.type; 
    let validExtensions = ["video/mp4"];
    if (validExtensions.includes(fileType)) {  

        files = this.files;
        myVideos.push(files[0]);

        var video = document.createElement('video');
        video.preload = 'metadata';

        video.onloadedmetadata = function () {
            window.URL.revokeObjectURL(video.src);
            var duration = video.duration;
            myVideos[myVideos.length - 1].duration = duration;
            updateInfos();
        }

        video.src = URL.createObjectURL(files[0]);;



        function updateInfos() {
            var infos = document.getElementById('infos');
            infos.textContent = "";
            for (var i = 0; i < myVideos.length; i++) {
                infos.textContent = myVideos[i].duration + 'n';
                document.getElementById('Label1').textContent = myVideos[i].duration;
//no matter what i wrote it really didn't work
            }
        }


    }
    else {
        alert("This is not an Image File!");
        dropArea.classList.remove("active");
        dragText.textContent = "Drag & Drop to Upload File";

    }

}

Blockquote default.aspx

<form id="form1" runat="server">
<span id="Message" runat="server"></span>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

    <asp:Label ID="Label1" runat="server" Text="Label" ViewStateMode="Enabled"></asp:Label>
</form>
<div> <div class="drag-area">
    <div id="input-upload-file" class="box-shadow">
                            <input type="file" class="upload" id="fileUp" name="fileUpload" accept="video/mp4" hidden />
        <button>Browse File</button>
               <pre id="infos" runat="server"></pre>
    </div>
   </div> 
</div>

Blockquote default.aspx.cs

protected void Button1_Click(object sender, EventArgs e)
{
    Response.Write("<script language=javascript>alert('" + Label1.Text + "');</script>");
 } 

I’m doing a project with Javascript and Asp.net that will run local with local files
Is there anyone who can fix the above codes for me, I would really appreciate it, I couldn’t solve it for 3 days

gives me empty value

I can’t send a picture

ReactJS increment counter becoming jumpy

this is a snippet of the react component. It increases to a point then it gets jumpy with random increment.

import React, { useState } from "react";

function CountUp(){

    const [count, setCount] = useState(0)

    function addCount(){
        setInterval(
            () => 
                // console.log(count) 
                setCount(count + 1) , 1000)
    }

    addCount()

    return (
            <div>
                <center>
                    <h4 className="time-text">{count}</h4>
                </center>
            </div>
    )
}


export default CountUp