Home > Software engineering >  How do I make Javascript (node.js) wait while I submit the form?
How do I make Javascript (node.js) wait while I submit the form?

Time:04-01

I would like the program/script to stop/wait after "console.log ('3')" until you click "Finished!" (and prior download of data from the above form). Clicking this button would be equivalent to restarting the program / script from "console.log ('4')". How can this be achieved?

code in app.js:

var express = require('express');
var http = require('http');
var path = require("path");
var helmet = require('helmet');
var rateLimit = require("express-rate-limit");
const port = process.env.PORT || 3000;
const { MongoClient, ServerApiVersion } = require('mongodb');
const { body, validationResult } = require('express-validator');
const { title } = require('process');
 
const app = express(),
    { engine } = require('express-handlebars'),
    bodyParser = require('body-parser');
 
app.set('view engine', 'hbs');
 
app.use(express.static("public"));
 
app.use(express.json({ extended: false }));
 
//app.use(bodyParser({ extended: false }))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.engine('handlebars', engine({
    defaultLayout: 'main'
}))
app.set('view engine', 'handlebars')
 
async function readingFromForm() {
    console.log('data download has started');
    console.log('3');
    app.post('/added', function(sReq, sRes) {
        var newTitle = sReq.body.title;
        console.log('title:', newTitle);
 
        var newAuthor = sReq.body.author;
        console.log('author:', newAuthor);
 
        var newMood = sReq.body.mood;
        console.log('mood:', newMood);
 
        var newTime = sReq.body.time;
        console.log('time:', newTime);
 
        var newDate = sReq.body.date;
        console.log('date:', newDate);
 
        sRes.sendStatus(200);
 
        console.log(sReq); //Caution! It generates a lot of "spam" in the console !!!
        console.log(sRes); //Caution! It generates a lot of "spam" in the console !!!
 
    });
    console.log('4');
    console.log('data has been downloaded');
}
 
async function main() {
 
    const uri = "mongodb srv://rafal:[email protected]/cattu?retryWrites=true&w=majority";
 
    const client = new MongoClient(uri);
 
    try {
        console.log('START');
        console.log('1');
        await client.connect(); // Connect to the MongoDB cluster
 
        console.log('2');
        await readingFromForm();
 
        console.log('5');
        await createListing(client, {
            title: "newTitle",
            author: "newAuthor",
            mood: "newMood",
            time: "newTime",
            date: "newDate" // YYYY-MM-DD
        })
        console.log('END');
 
    } catch (e) {
        console.error(e);
    } finally {
 
        await client.close();
    }
}
main().catch(console.error);
async function createListing(client, newListing) {
 
    const result = await client.db("cattu").collection("test1").insertOne(newListing);
    console.log(`New listing created with the following id: ${result.insertedId}`);
}
 
app.listen(port);

code in public/index.html

<!doctype html>
<html>
 
<head>
    <meta charset="utf-8">
    <title>Cattu</title>
    <link rel="stylesheet" href="styl.css">
    <link rel="icon" type="image/x-icon" href="favicon.png">
</head>
 
<body>
 
    <ul>
        <li><a href="#home">Start</a></li>
        <li><a href="#form">Formularz</a></li>
    </ul>
 
    <div id="poraDnia">
        <div id="bgchange">
 
 
            <div >
 
                <form method="POST" action="/added">
 
                    Podaj tytuł piosenki<br>
                    <input type="text" id="tytul" name="title" size="20px" required><br><br> Podaj wykonawcę<br>
                    <input type="text" id="wykonawca" name="author" size="20px" required><br><br> W jakim Jesteś nastroju?
                    <br>
                    <input type="checkbox" id="wesoly" value="wesoly" name="mood">
                    <label for="wesoly"> Wesoły/a </label><br>
 
                    <input type="checkbox" id="smutny" value="smutny" name="mood">
                    <label for="smutny"> Smutny/a </label><br>
 
                    <input type="checkbox" id="znudzony" value="znudzony" name="mood">
                    <label for="znudzony"> Znudzony/a </label><br>
 
                    <input type="checkbox" id="zmeczony" value="zmeczony" name="mood">
                    <label for="zmeczony"> Zmęczony/a </label><br>
 
                    <input type="checkbox" id="zdenerwowany" value="zdenerwowany" name="mood">
                    <label for="zdenerwowany"> Zdenerwowany/a </label><br>
 
                    <input type="checkbox" id="radosny" value="radosny" name="mood">
                    <label for="radosny"> Radosny/a </label><br>
 
                    <input type="checkbox" id="neutralny" value="neutralny" name="mood">
                    <label for="neutralny"> Neutralny/a </label><br>
 
                    <br>
 
                    <label for="pora"> Podaj porę dnia </label><br>
                    <select name="time" id="pora" required>
                        <option value="rano">Rano</option>
                        <option value="poludnie">Południe</option>
                        <option value="wieczor">Wieczór</option>
                        <option value="noc">Noc</option>
                        <option value="nie_pam">Nie pamiętam</option>
                    </select><br><br>
 
                    <label for="pora"> Podaj datę </label><br>
                    <input name="date" type="date"><br><br>
 
 
                    <button type="submit" >Skończone!</button>
                    <button type="reset" >Resetuj!</button>
 
                </form>
 
            </div>
 
            <div >
 
                <div id="tlo3" onm ouseover="rotatemoon(this)" onm ouseout="rotatemoonB(this)">
                    <div id="obiekt_glowny3" onm ouseover="movein(this)" onm ouseout="moveout(this)">
                        <div id="ksiezyc_srodek"></div>
                    </div>
                </div>
                <div id="tloGwiazdy1">
                    <div id="gwiazda1"></div>
                    <div id="gwiazda2"></div>
                    <div id="gwiazda3"></div>
                </div>
                <div id="tloGwiazdy2">
                    <div id="gwiazda11"></div>
                    <div id="gwiazda12"></div>
                    <div id="gwiazda13"></div>
                </div>
 
 
                <div id="tlo2">
                    <div id="obiekt_glowny2" onm ouseover="bigSun(this)" onm ouseout="smolSun(this)">
                        <div id="promien1"></div>
                        <div id="promien2"></div>
                        <div id="promien3"></div>
                        <div id="promien4"></div>
                        <div id="promien5"></div>
                        <div id="promien6"></div>
                        <div id="promien7"></div>
                        <div id="promien8"></div>
                        <div id="promien9"></div>
                        <div id="promien0"></div>
                    </div>
                </div>
 
                <div id="tlo1">
                    <div id="obiekt_glowny1">
                        <div id="slonce" onm ouseover="blouClounds(this)" onm ouseout="whiteClounds(this)">
                            <div id="promien11"></div>
                            <div id="promien12"></div>
                            <div id="promien13"></div>
                            <div id="promien14"></div>
                        </div>
                    </div>
                    <div id="chmura1"></div>
                    <div id="chmura2"></div>
                </div>
 
            </div>
 
            <div >
 
                <a href=""><br><br><br><br><br><br><br><br><br>Zobacz pełną historię</a>
            </div>
            <div >
 
                <!-- Tutaj chcemy pobierać dane z bazy żeby móc je wyświetlić (pobierać może zewnętrzny skrypt) -->
                *Dane pobrane z bazy*
 
            </div>
 
        </div>
    </div>
 
    <script src="script1.js"></script>
 
</body>
 
</html>

CodePudding user response:

use on click event handler in form. It will only submit the form when submit event will occur.

use onsubmit in form tag and an event handler in js.

CodePudding user response:

I think you need to understand client-server communication, server should be ready to handle request whenever client made,

You may update your readingFromForm function to call createListing like

async function readingFromForm(client) {
    console.log('data download has started');
    console.log('3');
    app.post('/added', function(sReq, sRes) {
        var bodyData = sReq.body;
        await createListing(client, bodyData);
        sRes.sendStatus(200);
        // sReq is an request object contains all request related information(data, objects & functions)
        // sRes is an response object contains all response related information(data, objects & functions)
 
    });
    console.log('4');
    console.log('data has been downloaded');
}

and in the main function, you need to pass client object to readingFromForm function like

 // await readingFromForm();
 await readingFromForm(client);
  • Related