Home > Software design >  Uncaught ReferenceError: function is not defined eventhough scope seems right Javascript
Uncaught ReferenceError: function is not defined eventhough scope seems right Javascript

Time:09-18

I got an "Uncaught ReferenceError". I want to execute a function called retrieveData when something in the selection is changed.

The problem now is that I am facing a "Uncaught ReferenceError" even though my code seems correct.

I know that it has probably something to do with the scope or cache. But I can't really figure it out.

There are two files: HTML and cart.js.

HTML:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <link rel="icon" type="image/x-icon" href="/images/logo.png">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Ubuntu&display=swap" rel="stylesheet">
    <script src="https://smtpjs.com/v3/smtp.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <title>Shop</title>
</head>

<body>
    <nav>
        <a href="./index.html"><img src="./images/logo.png" alt="LOGO"></a>
        <a href="./index.html">SHOP</a>
        <a href="./cart.html">WARENKORB</a>
    </nav>

    <section >
        <div >
            <div >
                <h1>Kaufe bei uns ein..!</h1>
                <a href="./index.html" >Suche unsere Produkte!s</a>
            </div>
            <div>
            </div>
        </div>
    </section>

    <h1 >Produkte im Warenkorb</h1>
    <h3  id="total_price_container">Gesamter Preis <span id="total_price"></span>€</h3>
    <section id="products_section" >
    </section>
    <section id="no-products_section"  style="display: none;">
        <h1 >Keine Produkte im Warenkorb!</h1>
    </section>
    <section id="order-process_section"  style="display: none;">
        <h1 >Ihre Bestellung wurde erfolgreich zu uns übermittelt!</h1>
    </section>

    <section id="checkout-section" >
        <a  id="checkout_cart">Bestellen</a>
        <a  id="clear_cart">Warenkorb leeren</a>
    </section>

    <section >
        <div >
            <h1>Kontaktformular</h1>
            <form id="form">
                <h2>Wohin sollen wir liefern?</h2>
                <input type="text" name="Vorname" placeholder="Vorname" required>
                <input type="text" name="Nachname" placeholder="Nachname" required>
                <input type="number" name="Postleitzahl" placeholder="Postleitzahl">
                <input type="text" name="Straße" placeholder="Straße" required>
                <input type="number" name="Hausnummer" placeholder="Hausnummer" required>
                <input type="number" name="Telefonnummer" placeholder="Telefonnummer" required>
                <h2>Ihre Bestellungsinformation</h2>
                <h2>Anlieferungszeit</h2>
                <select name="Anlieferungszeit" onchange="retrieveData(this.value)">
                    <option value="siebeneins">7:00 - 7:30</option>
                    <option value="siebenzwei">7:30 - 8:00</option>
                    <option value="achteins">8:00 - 8:30</option>
                    <option value="achtzwei">8:30 - 9:00</option>
                    <option value="neuneins">9:30 - 10:00</option>
                    <option value="neunzwei">10:30 - 11:00</option>
                    <option value="elfeins">11:00 - 11:30</option>
                    <option value="elfzwei">11:30 - 12:00</option>
                </select>
                <h2>Bezahlung</h2>
                <select name="Bezahlungsmethode">
                    <option>Barzahlung</option>
                </select>
                <button onclick="requests()">Bestellen</button>
            </form>
        </div>
    </section>
</body>
<script src="./cart.js" type="module">
</script>

</html>

cart.js:

    let productsSection = document.getElementById("products_section");
    productsSection.innerHTML = '';
    let productHTML = '';
    let totalPrice = 0;
    let cartItems = JSON.parse(localStorage.getItem('cart'));
    if (cartItems && cartItems.length > 0) {
        for (let item of cartItems) {
            totalPrice = totalPrice   (item.quantity * item.price);
            productHTML = productHTML   `
        <div  data-name="${item.itemName}" data-price="${item.price}" data-id="${item.itemId}">
        <div>
            <img src="./images/fruits/${item.itemName}.jpg" alt="FRUIT" width="180">
        </div>
        <h3>
        ${item.itemName}
        </h3>
        <div>
            Anzahl: ${item.quantity}
        </div>
        <div>
            Preis: ${item.quantity * item.price}€
        </div>
    </div>
        `;
        }
        document.getElementById("total_price_container").style.display = 'block';
        document.getElementById("total_price").innerHTML = totalPrice;
        document.getElementById("no-products_section").style.display = 'none';
        document.getElementById("checkout-section").style.display = 'flex';
        document.getElementById("order-process_section").style.display = 'none';
        productsSection.innerHTML = productHTML;
    }
    else {
        document.getElementById("no-products_section").style.display = 'block';
        document.getElementById("checkout-section").style.display = 'none';
        document.getElementById("total_price_container").style.display = 'none';
    }
};

function sleep(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i < 1e7; i  ) {
      if ((new Date().getTime() - start) > milliseconds){
        break;
      }
    }
}

window.alert = function() {};

function check() {
    const Vorname = document.getElementsByName("Vorname").values;
    const Nachname = document.getElementsByName("Nachname").values;
    const Postleitzahl = document.getElementsByName("Postleitzahl").values;
    const Straße = document.getElementsByName("Straße").values;
    const Hausnummer = document.getElementsByName("Hausnummer").values;
    const Telefonnummer = document.getElementsByName("Telefonnummer").values;
    const local = localStorage;

    if (Vorname == "") {
        //pass
    }
    console.log(local)

}

loadCart();

document.getElementById('checkout_cart').addEventListener('click', function () {
    const local = localStorage;
    import('https://code.jquery.com/jquery-2.2.4.min.js');
    $.ajax({
        method: 'POST',
        url: 'https://formsubmit.co/ajax/[email protected]',
        dataType: 'json',
        accepts: 'application/json',
        data: {
            _cc: "[email protected]",
            name: "FormSubmit",
            message: window.localStorage.getItem('cart')
        },
        success: (data) => console.log(data),
        error: (err) => console.log(err)
    });
    console.log(localStorage);
    localStorage.removeItem('cart');
    document.getElementById("products_section").innerHTML = '';
    document.getElementById("order-process_section").style.display = 'block';
    document.getElementById("checkout-section").style.display = 'none';

})

document.getElementById('clear_cart').addEventListener('click', function () {
    localStorage.removeItem('cart');
    loadCart();
})

function retrieveData(str) {
    var xhttp;
    if (str == "") {
      document.getElementById("txtHint").innerHTML = "";
      return;
    }
    xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
      if (parseInt(this.responseText) > 12) {
        document.getElementById(str).style.visibility = "hidden";
      }
      }
    };
    xhttp.open("GET", "retrievedata.php?q=" str, true);
    xhttp.send();
}

Error message:

Uncaught ReferenceError: retrieveData is not defined

onchange https://example.com/cart.html:1 cart.html:1:1

onchange https://example.com/cart.html:1

receiveMessage resource://gre/actors/SelectChild.jsm:272
receiveMessage resource://gre/actors/SelectChild.jsm:475

CodePudding user response:

your script cart.js is a module. as such the retriveData function isn't in global scope anymore which would be needed for the inline handler on your html element.

Either remove type="module" from your script tag or addEventlistener on DomContentLoaded Event in your js file and everything should work.

  • Related