0

I fetched a login form asynchronously, and setted it inside document.body. I declared it's on submit form before that, and now getting a Reference error. Is there any way to set onsubmit using html, without having to call loginForm.onsubmit = login. In chrome inspector sources, even after setting /session in body, it still shows original index.html code.

Bellow you will find public/js/app.js

const result = await fetch('/session');

if (result) {
    const login = await result.text();
    document.body.innerHTML = login;
}

function login(e) {
    e.preventDefault();
    const loginForm = document.getElementById('loginForm');
    console.log(loginForm);
    const options = { method: loginForm.method, body: new FormData(loginForm) };
    const loginButton = document.getElementById('loginButton');
    const loginButtonHTML = loginButton.innerHTML;
    loginButton.innerHTML = 'Loading...';
    disableElements(loginForm);
    // const result = await fetch(loginForm.action, options);
}

The html returned from /session is

<form id="loginForm" action="/user/login" method="post" onsubmit="login(event)">
    <input type="text" name="username" autocomplete="username" placeholder="Username">
    <input type="password" name="password" autocomplete="current-password" placeholder="Password">
    <button id="loginButton" type="submit">Login</button>
</form>

The complete error code is: Uncaught ReferenceError: login is not defined at HTMLFormElement.onsubmit ((index):1:1)

The original html page which includes with the script index.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">
    <title>Aveloz</title>
    <link rel="stylesheet" href="public/css/style.css">
</head>

<body>
    <div>
        <h1 style="text-align: center;">Loading...</h1>
    </div>

<script type="module" src="public/js/app.js"></script>
</body>

</html>

1 Answers1

0

Since you import the javascript as a module, you need to export the login function:

export function login(e) {
...

you'd then have to import into you html from something that isn't a module:

import { login } from './public/js/app.js';
Garr Godfrey
  • 8,257
  • 2
  • 25
  • 23