• Najnowsze pytania
  • Bez odpowiedzi
  • Zadaj pytanie
  • Kategorie
  • Tagi
  • Zdobyte punkty
  • Ekipa ninja
  • IRC
  • FAQ
  • Regulamin
  • Książki warte uwagi

Błąd w wyświetlaniu wyniku po wykonaniu skryptu

Object Storage Arubacloud
+1 głos
252 wizyt
pytanie zadane 29 stycznia 2022 w JavaScript przez trixter310 Obywatel (1,440 p.)

Ma ktoś może pojęcie dlaczego po wykonanych wyliczeniach zamiast wyniku pojawia się wszędzie NaN zamiast wyniku?

<?php
  
    session_start();
      
    if (!isset($_SESSION['zalogowany']))
    {
        header('Location: index.php');
        exit();
    }
    require_once "connection.php";
 
    $polaczenie = new mysqli($host, $db_user, $db_password, $db_name);
    if ($polaczenie->connect_errno)
    {
       throw new Exception(mysqli_connect_errno());
    }
    $sql = "SELECT gender FROM uzytkownicy WHERE id='".$_SESSION['zalogowany_id']."'";
    if ($rezultat = $polaczenie->query($sql))
    {
       $wynik = $rezultat->fetch_assoc();
       $plec = $wynik['gender'];
    } 
 
?>
<!DOCTYPE html>
<html lang="pl">
<head>
<?php include('templates/head.php'); ?> 
 
<script>
    function calc() {
    let A = document.getElementById("age").value;
    let W = document.getElementById("weight").value;
    let H = document.getElementById("height").value;
  
    let S, R, activity;
    let P = "<?php echo $plec; ?>";
  
  
   
    if (document.getElementById("age").value.length == 0) {
  
        document.getElementById("ATT").style = "color: red;"
        document.getElementById("WTT").style = "display: none;"
        document.getElementById("HTT").style = "display: none;"
  
        return
  
    }
  
    if (document.getElementById("weight").value.length == 0) {
  
        document.getElementById("ATT").style = "display: none;"
        document.getElementById("HTT").style = "display: none;"
        document.getElementById("WTT").style = "color: red;"
          
        return
  
    }
  
    if (document.getElementById("height").value.length == 0) {
  
        document.getElementById("ATT").style = "display: none;"
        document.getElementById("WTT").style = "display: none;"
        document.getElementById("HTT").style = "color: red;"
          
        return
  
    }
  
 if (document.getElementById("male")) {
        S =  Math.round((9.99*W)+(6.25*H)-(4.92*A)+5)
        //P = "mężczyzna"
    } 
    else if (document.getElementById("female")) {
        S =  Math.round((9.99*W)+(6.25*H)-(4.92*A)-161)
        //P = "kobieta"
    }
    
    if (document.getElementById("0").selected) {
        R = S
    }
  
    
    if (document.getElementById("1").selected) {
        R = S*1.2
        activity = "1. Niewielka/Brak treningów"
  
    }
  
   
    if (document.getElementById("2").selected) {
        R = S*1.35
        activity = "2. Niska aktywność (treningi 1-3 razy/tydzień)"
    }
  
     
    if (document.getElementById("3").selected) {
        R = S*1.55
        activity = "3. Średnia aktywność (codzienna aktywność lub intensywne treningi 3-4 razy/tydzień)"
  
    }
      
    
    if (document.getElementById("4").selected) {
        R = S*1.75
        activity = "4. Wysoka aktywność (intensywne treningi 6-7 razy/tydzień)"
  
    }
  
  
    if (document.getElementById("5").selected) {
        R = S*1.95
        activity = "5. Bardzo wysoka aktywność (codzienne bardzo intensywne treningi lub praca fizyczna)"
  
    }
  
    document.getElementById("ATT").style = "display: none;"
    document.getElementById("HTT").style = "display: none;"
    document.getElementById("WTT").style = "display: none;"
  
    document.getElementById("age").placeholder = " "
    document.getElementById("weight").placeholder = "Kg"
    document.getElementById("height").placeholder = "Cm"
  
    document.getElementById("a").innerHTML = Math.round(R)
    document.getElementById("b").innerHTML = Math.round(R*0.80)
    document.getElementById("c").innerHTML = Math.round(R*1.20)
  
  
    document.getElementById("ak").innerHTML = Math.round(R)
    document.getElementById("ak-2").innerHTML = Math.round(S)
    document.getElementById("a-1k").innerHTML = Math.round((R*0.80)*0.25)
    document.getElementById("a-1g").innerHTML = Math.round(((R*0.80)*0.25)/4)
    document.getElementById("a-2k").innerHTML = Math.round((R*0.80)*0.50)
    document.getElementById("a-2g").innerHTML = Math.round(((R*0.80)*0.50)/4)
    document.getElementById("a-3k").innerHTML = Math.round((R*0.80)*0.25)
    document.getElementById("a-3g").innerHTML = Math.round(((R*0.80)*0.25)/9)
  
  
  
  
  
    document.getElementById("bk").innerHTML = Math.round(R)
    document.getElementById("bk-2").innerHTML = Math.round(S)
    document.getElementById("b-1k").innerHTML = Math.round((R*0.80)*0.25)
    document.getElementById("b-1g").innerHTML = Math.round(((R*0.80)*0.25)/4)
    document.getElementById("b-2k").innerHTML = Math.round((R*0.80)*0.50)
    document.getElementById("b-2g").innerHTML = Math.round(((R*0.80)*0.50)/4)
    document.getElementById("b-3k").innerHTML = Math.round((R*0.80)*0.25)
    document.getElementById("b-3g").innerHTML = Math.round(((R*0.80)*0.25)/9)
    document.getElementById("bs").innerHTML = Math.round(R-(R*0.80))
  
  
    document.getElementById("ck").innerHTML = Math.round(R)
    document.getElementById("ck-2").innerHTML = Math.round(S)
    document.getElementById("c-1k").innerHTML = Math.round((R*1.20)*0.25)
    document.getElementById("c-1g").innerHTML = Math.round(((R*1.20)*0.25)/4)
    document.getElementById("c-2k").innerHTML = Math.round((R*1.20)*0.50)
    document.getElementById("c-2g").innerHTML = Math.round(((R*1.20)*0.50)/4)
    document.getElementById("c-3k").innerHTML = Math.round((R*1.20)*0.25)
    document.getElementById("c-3g").innerHTML = Math.round(((R*1.20)*0.25)/9)
    document.getElementById("cs").innerHTML = Math.round((R*1.20)-R)
  
    document.getElementById("Final").style = " margin: auto; margin-top: 1em; border-radius: 20px; margin-bottom: 30px"
  
  
    if (document.getElementById("more").selected) {
        document.getElementById("less-text-1").style = "display: none;"
        document.getElementById("less-text-2").style = "display: none;"
        document.getElementById("constant-text-1").style = "display: none;"
        document.getElementById("constant-text-2").style = "display: none;"
        document.getElementById("more-text-1").style = "display: block;"
        document.getElementById("more-text-2").style = "display: table-row;"
        document.getElementById("more-text-1").scrollIntoView();
        dataLayer.push({
            'event': 'calc',
            'cel': 'chce przytyć',
            'waga': W,
            'wiek': A,
            'wzrost' : H,
            'płeć' : P,
            'aktywność' : activity
        });
  
    }
    if (document.getElementById("less").selected) {
        document.getElementById("more-text-1").style = "display: none;"
        document.getElementById("more-text-2").style = "display: none;"
        document.getElementById("constant-text-1").style = "display: none;"
        document.getElementById("constant-text-2").style = "display: none;"
        document.getElementById("less-text-1").style = "display: block;"
        document.getElementById("less-text-2").style = "display: table-row;"
        document.getElementById("less-text-1").scrollIntoView();
        dataLayer.push({
            'event': 'calc',
            'cel': 'chce schudnąć',
            'waga': W,
            'wiek': A,
            'wzrost' : H,
            'płeć' : P,
            'aktywność' : activity
        });
  
    }
    if (document.getElementById("constant").selected) {
        document.getElementById("more-text-1").style = "display: none;"
        document.getElementById("more-text-2").style = "display: none;"
        document.getElementById("less-text-1").style = "display: none;"
        document.getElementById("less-text-2").style = "display: none;"
        document.getElementById("constant-text-1").style = "display: block;"
        document.getElementById("constant-text-2").style = "display: table-row;"
        document.getElementById("constant-text-1").scrollIntoView();
        dataLayer.push({
            'event': 'calc',
            'cel': 'utrzymanie wagi',
            'waga': W,
            'wiek': A,
            'wzrost' : H,
            'płeć' : P,
            'aktywność' : activity
        });
  
       
    }
} 
</script>

gender jest pobrany z bazy danych gdzie jest albo male albo female

2 odpowiedzi

+2 głosów
odpowiedź 29 stycznia 2022 przez CubeStorm Pasjonat (15,020 p.)

NaN - Not a Number.

Nie zagłębiałem się w Twój kod, ale obstawiam, że pobierasz z inputa jakąś liczbę, ale jest ona typu string, a obliczenia możesz tworzyć tylko na typach Number, przykład:

Błędne użycie:

const a = '12';
const b = '15';

const c = a * b; // Próbujesz pomnożyć wartości typu string

Poprawne użycie:

const a = 12;
const b = 15

const c = a * b; // Poprawne działanie na typach Number

Poprawne użycie z opcją parsowania, którą Ci polecam:

const a = '12';
const b = '15';

// Działanie na zmiennych typu string, ale z opcją rzutowaniach ich na typ Number
const c = Number(a) * Number(b);

 

2
komentarz 29 stycznia 2022 przez ScriptyChris Mędrzec (190,190 p.)

Błędne użycie:

// Próbujesz pomnożyć wartości typu string

I tak i nie. :) Tzn. mnożenie będzie działać również na liczbie w postaci stringa, ale fakt że lepiej (bezpieczniej i czytelniej) jawnie to parsować niż się zdziwić. Użycie operatora mnożenia spowoduje niejawne parsowanie wartości na liczbę, więc w każdym z przypadków:

  • "12" * 15
  • 12 * "15"
  • "12" * "15"
  • 12 * 15

wynikiem będzie 180. Chyba, że dana wartość nie daje się sparsować na liczbę, wtedy wynikiem będzie NaN. O ile się orientuję, to jedynym operatorem arytmetycznym, który traktuje obie strony jak string jest (plus), stąd (niesławne przykłady) np. "12" + 15 to "1215" a nie 27.

komentarz 29 stycznia 2022 przez trixter310 Obywatel (1,440 p.)

@CubeStorm, to znaczy obliczenia wychodziły do momentu, w którym zamiast używać opcji w formularzu wybierania płci. pobrałem ją z bazy. wtedy wychodzi wynik NaN

komentarz 29 stycznia 2022 przez CubeStorm Pasjonat (15,020 p.)
Używaj console.log() dla tej wartości po kolei w każdym miejscu.

Na którym miejscu konkretnie wychodzi NaN?

Jeśli płeć nie ma wpływu na inne obliczenia to znaczy, że nie w tym miejscu leży wina.
komentarz 29 stycznia 2022 przez trixter310 Obywatel (1,440 p.)
płeć ma wpływ, bo w zależności od tego czy to mężczyzna czy kobieta mnoży się przez co innego
0 głosów
odpowiedź 29 stycznia 2022 przez VBService Ekspert (253,340 p.)

obliczenia wychodziły do momentu, w którym zamiast używać opcji w formularzu wybierania płci. pobrałem ją z bazy. wtedy wychodzi wynik NaN

 

Sprawdź co zwraca baza danych i przypisuje do (lub nie przypisuje - błąd w zapytaniu sql) do zmiennej $plec, dopisz w linii 23

var_dump($plec);

 

i zamień w linii 71 na

if (P == "mężczyzna")
    S =  Math.round((9.99*W)+(6.25*H)-(4.92*A)+5);
else if (P == "kobieta")
    S =  Math.round((9.99*W)+(6.25*H)-(4.92*A)-161);

 

bo do P masz przypisaną wartość, linia 37

let P = "<?php echo $plec; ?>";

 

 zamiast używać opcji w formularzu wybierania płci. pobrałem ją z bazy

 

wtedy element od id - "male" lub "female" jest nie ustawiony i nie wykonuje się kod warunku

if (document.getElementById("male")) {
    S =  Math.round((9.99*W)+(6.25*H)-(4.92*A)+5)
    //P = "mężczyzna"
} 
else if (document.getElementById("female")) {
     S =  Math.round((9.99*W)+(6.25*H)-(4.92*A)-161)
     //P = "kobieta"
}

przez co zmienna S nie posiada żadnej wartości.

komentarz 29 stycznia 2022 przez trixter310 Obywatel (1,440 p.)

pozmieniałem tak jak powiedziałeś i wyświetla mi się w konsoli: Uncaught ReferenceError: dataLayer is not defined

<?php
  
    session_start();
      
    if (!isset($_SESSION['zalogowany']))
    {
        header('Location: index.php');
        exit();
    }
    require_once "connection.php";
 
    $polaczenie = new mysqli($host, $db_user, $db_password, $db_name);
    if ($polaczenie->connect_errno)
    {
       throw new Exception(mysqli_connect_errno());
    }
    $sql = "SELECT gender FROM uzytkownicy WHERE id='".$_SESSION['zalogowany_id']."'";
    if ($rezultat = $polaczenie->query($sql))
    {
       $wynik = $rezultat->fetch_assoc();
       $plec = $wynik['gender'];
       var_dump($plec);
    } 
 
?>
<!DOCTYPE html>
<html lang="pl">
<head>
<?php include('templates/head.php'); ?> 
 
<script>
    function calc() {
    let A = document.getElementById("age").value;
    let W = document.getElementById("weight").value;
    let H = document.getElementById("height").value;
  
    let S, R, activity;
    let P = "<?php echo $plec; ?>";
  
  
   
    if (document.getElementById("age").value.length == 0) {
  
        document.getElementById("ATT").style = "color: red;"
        document.getElementById("WTT").style = "display: none;"
        document.getElementById("HTT").style = "display: none;"
  
        return
  
    }
  
    if (document.getElementById("weight").value.length == 0) {
  
        document.getElementById("ATT").style = "display: none;"
        document.getElementById("HTT").style = "display: none;"
        document.getElementById("WTT").style = "color: red;"
          
        return
  
    }
  
    if (document.getElementById("height").value.length == 0) {
  
        document.getElementById("ATT").style = "display: none;"
        document.getElementById("WTT").style = "display: none;"
        document.getElementById("HTT").style = "color: red;"
          
        return
  
    }
  
    if (P == "male")
    S =  Math.round((9.99*W)+(6.25*H)-(4.92*A)+5);
    else if (P == "female")
    S =  Math.round((9.99*W)+(6.25*H)-(4.92*A)-161);

    
    if (document.getElementById("0").selected) {
        R = S
    }
  
    
    if (document.getElementById("1").selected) {
        R = S*1.2
        activity = "1. Niewielka/Brak treningów"
  
    }
  
   
    if (document.getElementById("2").selected) {
        R = S*1.35
        activity = "2. Niska aktywność (treningi 1-3 razy/tydzień)"
    }
  
     
    if (document.getElementById("3").selected) {
        R = S*1.55
        activity = "3. Średnia aktywność (codzienna aktywność lub intensywne treningi 3-4 razy/tydzień)"
  
    }
      
    
    if (document.getElementById("4").selected) {
        R = S*1.75
        activity = "4. Wysoka aktywność (intensywne treningi 6-7 razy/tydzień)"
  
    }
  
  
    if (document.getElementById("5").selected) {
        R = S*1.95
        activity = "5. Bardzo wysoka aktywność (codzienne bardzo intensywne treningi lub praca fizyczna)"
  
    }
  
    document.getElementById("ATT").style = "display: none;"
    document.getElementById("HTT").style = "display: none;"
    document.getElementById("WTT").style = "display: none;"
  
    document.getElementById("age").placeholder = " "
    document.getElementById("weight").placeholder = "Kg"
    document.getElementById("height").placeholder = "Cm"
  
    document.getElementById("a").innerHTML = Math.round(R)
    document.getElementById("b").innerHTML = Math.round(R*0.80)
    document.getElementById("c").innerHTML = Math.round(R*1.20)
  
  
    document.getElementById("ak").innerHTML = Math.round(R)
    document.getElementById("ak-2").innerHTML = Math.round(S)
    document.getElementById("a-1k").innerHTML = Math.round((R*0.80)*0.25)
    document.getElementById("a-1g").innerHTML = Math.round(((R*0.80)*0.25)/4)
    document.getElementById("a-2k").innerHTML = Math.round((R*0.80)*0.50)
    document.getElementById("a-2g").innerHTML = Math.round(((R*0.80)*0.50)/4)
    document.getElementById("a-3k").innerHTML = Math.round((R*0.80)*0.25)
    document.getElementById("a-3g").innerHTML = Math.round(((R*0.80)*0.25)/9)
  
  
  
  
  
    document.getElementById("bk").innerHTML = Math.round(R)
    document.getElementById("bk-2").innerHTML = Math.round(S)
    document.getElementById("b-1k").innerHTML = Math.round((R*0.80)*0.25)
    document.getElementById("b-1g").innerHTML = Math.round(((R*0.80)*0.25)/4)
    document.getElementById("b-2k").innerHTML = Math.round((R*0.80)*0.50)
    document.getElementById("b-2g").innerHTML = Math.round(((R*0.80)*0.50)/4)
    document.getElementById("b-3k").innerHTML = Math.round((R*0.80)*0.25)
    document.getElementById("b-3g").innerHTML = Math.round(((R*0.80)*0.25)/9)
    document.getElementById("bs").innerHTML = Math.round(R-(R*0.80))
  
  
    document.getElementById("ck").innerHTML = Math.round(R)
    document.getElementById("ck-2").innerHTML = Math.round(S)
    document.getElementById("c-1k").innerHTML = Math.round((R*1.20)*0.25)
    document.getElementById("c-1g").innerHTML = Math.round(((R*1.20)*0.25)/4)
    document.getElementById("c-2k").innerHTML = Math.round((R*1.20)*0.50)
    document.getElementById("c-2g").innerHTML = Math.round(((R*1.20)*0.50)/4)
    document.getElementById("c-3k").innerHTML = Math.round((R*1.20)*0.25)
    document.getElementById("c-3g").innerHTML = Math.round(((R*1.20)*0.25)/9)
    document.getElementById("cs").innerHTML = Math.round((R*1.20)-R)
  
    document.getElementById("Final").style = " margin: auto; margin-top: 1em; border-radius: 20px; margin-bottom: 30px"
  
  
    if (document.getElementById("more").selected) {
        document.getElementById("less-text-1").style = "display: none;"
        document.getElementById("less-text-2").style = "display: none;"
        document.getElementById("constant-text-1").style = "display: none;"
        document.getElementById("constant-text-2").style = "display: none;"
        document.getElementById("more-text-1").style = "display: block;"
        document.getElementById("more-text-2").style = "display: table-row;"
        document.getElementById("more-text-1").scrollIntoView();
        dataLayer.push({
            'event': 'calc',
            'cel': 'chce przytyć',
            'waga': W,
            'wiek': A,
            'wzrost' : H,
            'płeć' : P,
            'aktywność' : activity
        });
  
    }
    if (document.getElementById("less").selected) {
        document.getElementById("more-text-1").style = "display: none;"
        document.getElementById("more-text-2").style = "display: none;"
        document.getElementById("constant-text-1").style = "display: none;"
        document.getElementById("constant-text-2").style = "display: none;"
        document.getElementById("less-text-1").style = "display: block;"
        document.getElementById("less-text-2").style = "display: table-row;"
        document.getElementById("less-text-1").scrollIntoView();
        dataLayer.push({
            'event': 'calc',
            'cel': 'chce schudnąć',
            'waga': W,
            'wiek': A,
            'wzrost' : H,
            'płeć' : P,
            'aktywność' : activity
        });
  
    }
    if (document.getElementById("constant").selected) {
        document.getElementById("more-text-1").style = "display: none;"
        document.getElementById("more-text-2").style = "display: none;"
        document.getElementById("less-text-1").style = "display: none;"
        document.getElementById("less-text-2").style = "display: none;"
        document.getElementById("constant-text-1").style = "display: block;"
        document.getElementById("constant-text-2").style = "display: table-row;"
        document.getElementById("constant-text-1").scrollIntoView();
        dataLayer.push({
            'event': 'calc',
            'cel': 'utrzymanie wagi',
            'waga': W,
            'wiek': A,
            'wzrost' : H,
            'płeć' : P,
            'aktywność' : activity
        });
  
       
    }
} 
</script>

 

1
komentarz 29 stycznia 2022 przez trixter310 Obywatel (1,440 p.)
Znalazłem rozwiązanie dziękuję

Podobne pytania

0 głosów
1 odpowiedź 997 wizyt
pytanie zadane 2 maja 2020 w PHP przez tgv Użytkownik (890 p.)
0 głosów
1 odpowiedź 770 wizyt
0 głosów
2 odpowiedzi 181 wizyt

92,568 zapytań

141,422 odpowiedzi

319,638 komentarzy

61,957 pasjonatów

Motyw:

Akcja Pajacyk

Pajacyk od wielu lat dożywia dzieci. Pomóż klikając w zielony brzuszek na stronie. Dziękujemy! ♡

Oto polecana książka warta uwagi.
Pełną listę książek znajdziesz tutaj.

Akademia Sekuraka

Kolejna edycja największej imprezy hakerskiej w Polsce, czyli Mega Sekurak Hacking Party odbędzie się już 20 maja 2024r. Z tej okazji mamy dla Was kod: pasjamshp - jeżeli wpiszecie go w koszyku, to wówczas otrzymacie 40% zniżki na bilet w wersji standard!

Więcej informacji na temat imprezy znajdziecie tutaj. Dziękujemy ekipie Sekuraka za taką fajną zniżkę dla wszystkich Pasjonatów!

Akademia Sekuraka

Niedawno wystartował dodruk tej świetnej, rozchwytywanej książki (około 940 stron). Mamy dla Was kod: pasja (wpiszcie go w koszyku), dzięki któremu otrzymujemy 10% zniżki - dziękujemy zaprzyjaźnionej ekipie Sekuraka za taki bonus dla Pasjonatów! Książka to pierwszy tom z serii o ITsec, który łagodnie wprowadzi w świat bezpieczeństwa IT każdą osobę - warto, polecamy!

...