Home > OS >  JavaScript - Load new html page with button click
JavaScript - Load new html page with button click

Time:07-08

I am running an http server using Nodejs. Initially, there is a login page with a text entry where you enter a nickname and a button that will take you to a new html page.

The button adds the player with their nickname to the player list as it should. However, it does not load the new html page.

Here's the server code:

const http = require('http');
const fs = require('fs');

console.log('running');

let player_count = 0;
let players = [];

class player
{
    constructor(id)
    {
        this.id = id;
        this.name = "";
        this.card_czar = false;
        this.cards = new Set();
        this.score = 0;
        this.selection = "";
    }

    setName(nick_name)
    {
        this.name = nick_name;
    }

    setCardCzar(czar_boolean)
    {
        this.card_czar = czar_boolean;
    }

    delCard(card_val)
    {
        this.cards.delete(card_val);
    }

    addCard(card_val)
    {
        this.cards.add(card_val);
    }

    addScore()
    {
        this.score  ;
    }
}

let server = http.createServer(async (req, res) => {
    console.log(req.url);

    if (req.url == '/') {
        res.write(fs.readFileSync('../frontend/test.html'));
    }
    else if (req.url == '/login') {
        const buffers = [];

        for await (const chunk of req) {
            buffers.push(chunk);
        }

        let buffer = Buffer.concat(buffers).toString()
        const data = await JSON.parse(buffer);

        new_player = new player(player_count);
        new_player.setName(data.nickname);
        players.push(new_player);

        player_count  ;

        res.write(fs.readFileSync('../frontend/cardcast.html'));

        console.log(players)
    }

    res.end();
});

server.listen(3000);

and here's the client code:

<html>  
    <head>  
    <script type = "text/javascript">  
        async function login()
        {
            let nickname = document.getElementById('username-field').value;
            console.log(nickname);

            let url = window.location.href   'login';
            
            let res = await fetch(url, {
                method: 'post',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({nickname})
            });
        }
    </script>  
    </head>
    <style>
        .login-form-field {
        border: none;
        border-bottom: 1px solid #3a3a3a;
        border-top: 1px solid #3a3a3a;
        margin-bottom: 10px;
        border-radius: 3px;
        outline: none;
        padding: 0px 0px 5px 5px;
        }

        #login-form-submit {
        width: 100%;
        padding: 7px;
        border: none;
        border-radius: 5px;
        color: white;
        font-weight: bold;
        background-color: #3a3a3a;
        cursor: pointer;
        outline: none;
        }
    </style>
    <body>  
        <p>Welcome To Cards Against Mill House</p>
        <div id="New Accident" >
            <input type="text" name="username" id="username-field"  placeholder="Nickname">
  
            <button onclick = "login()" value = "Login">Login</button> 
        </div>
    </body>  
</html>  

The server file is in the backend folder and the file cardcast.html is in the frontend folder. I would like it to load the cardcast.html file after the player enters their nickname, so they could begin playing the game.

Any help accomplishing this would be greatly appreciated! Thanks in advance!

CodePudding user response:

I believe res on the client-side code should store the HTML response. Have you tried printing it to see what it holds?

You probably want to read this it goes over how to inject HTML from a fetch response.

CodePudding user response:

Your server handler of /login is supposed to return a value, which it does. It's the content of file cardcast.html. If you look at the Network tab you'll this is what happening. This content probably should have been a JSON, but nevertheless you do nothing with the response on client side.

What were you expecting to happen? If you wanted to load the page then you didn't need to use Ajax at all. You need to Redirect. Using a <form> tag would have eased the process.

// server, handle POST

if (req.url == '/login') {

  var nickname = req.body.username
  new_player = new player(player_count);
  new_player.setName(nickname);
  players.push(new_player);

  player_count  ;

  res.write(fs.readFileSync('../frontend/cardcast.html'));

  console.log(players)
}
<div id="New Accident" >
  <form action="/login" method="post">
    <input type="text" name="username" id="username-field"  placeholder="Nickname">

    <button value="Login">Login</button>
  </form>
</div>

  • Related