Benjamin-0-Dover
Benjamin-0-Dover

Reputation: 35

How to show javascript console output into an alert()

Everyday my teacher looks across the internet to find random facts for us then she writes on the board and we get to see it each day we go in her class. I'm trying to make a super simple website that once a button is clicked an alert at the top of the page appears. Whenever the fact I cant figure out how to make the console go to the alert. I've looked at a different other Stack question but i didn't really understand it. Here is my complete code. I'm sorry i just started javascript and literally couldn't be more new to it. Thanks in advance!

const express = require("express");
const app = express();
app.use(express.static("public"));
app.get("/", (request, response) => {
  response.sendFile(__dirname + "/facts.html");
});
const listener = app.listen(process.env.PORT, () => {
  console.log("Your app is listening on port " + listener.address().port);
});

var fact = require('random-fact');
fact();
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Generate Random Facts</title>
</head>
<body>
<h1>Fact Generator</h1>
<br><br><br><br>
<script>

function test() {
    alert('fact');
}

</script>
<input type="button" onclick="test()" value="Generate Random Fact!">
</body>
</html>

Upvotes: 1

Views: 4233

Answers (2)

destroyer22719
destroyer22719

Reputation: 404

I'm sorry if I'm not understanding your code properly but from my understanding the first code block, the NodeJS is sending a file on the root url. That root file is what you want to alert this "random fact"

However, the random fact data is stored in var fact = require("random-fact")

NodeJS is a JavaScript runtime environment. Meaning a place to execute JavaScript code, OUTSIDE the browser and in the server. NodeJS isn't like vanilla JS where you have access to the BOM and DOM.

However, with express you can set up what's called an endpoint. That endpoint will send the data on each request to each route which you can set up on the front end.

First off, I'm assuming the fact() function returns some data. We'll set up an endpoint:

app.get('/random-facts', (req, res) => res.send(fact()));

whenever we send a get request to /random-facts it'll execute the function and hopefully get what you want

On the frontend we need to do what's called an AJAX request. Where you send a request to the API. Like you do in your browser when you type www.google.com you send a get request. AJAX request can get more sophisticated with just GET requests but that's for something else.

We'll do that with JS using the fetch API

On your html you can do

<script>
fetch('http://localhost:3000/random-facts')
  .then(response => response.json())
  .then(data => alert(data));
</script>

This is probably a bit more advanced than what you know but I hope this helps

Upvotes: 2

alec wilson
alec wilson

Reputation: 176

Like someone else said, the JavaScript you have up there is server side NodeJS.

Instead, just use your HTML and statically host it on GitHub or something.

Here is an example of a random fact from a list of facts:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Generate Random Facts</title>
    </head>
    <body>
        <h1>Fact Generator</h1>
        <p id="fact"> </p>
        <script>
            // populate with multiple facts
            var facts = ["fact one", "fact two", "fact three", "fact four"];

            function alertFact() {
                const fact = returnFact()
                
                document.getElementById('fact').innerText = fact
                alert(fact);
            }

            function returnFact() {
                var fact = facts[Math.floor(Math.random() * facts.length)];

                return fact;
            }
        </script>
        <input type="button" onclick="alertFact()" value="Generate Random Fact!" />
    </body>
</html>

or you can view it here: https://jsfiddle.net/utdoLbj2/

Upvotes: 1

Related Questions