Search code examples
javascripthtmlnode.jsejsweb-development-server

How can we do late execution of an html code


I want the part of the html code to only execute when the above form is being submitted.

<body>
    <form action="/Recipes" method="post">
        <input type="text" name="recipeName" placeholder="Enter recipe Name" required>
        <button>Find</button>
    </form>
    <!-- The below code should only run once the above form is submitted and should not be executed on the page load -->

    <section class="GPT">
        <h1><%= Name %></h1>

        <% Instructions.forEach(function(instruction) { %>
            <ul><%= instruction %></ul>
        <% }); %>    

        <a href="/"><button>Home</button></a>
    </section>

</body>

Following are the technologies that I'm using:

  • NodeJS
  • EJS
  • JavaScript

I tried using functions in JavaScript that should only be called after the submission of the form.


Solution

  • I used an additional variable called submitted and set it to false on the page load.

    app.get('/Recipes', (req, res) => {
        // Render the EJS template with submitted set to false (initial page load)
        res.render('recipe', { submitted: false });
    });
    

    and set the submitted variable to true whenever the name of the recipe is entered and the form is submitted.

    app.post('/Recipes', (req, res) => {
    
        // Set submitted to true to render the specific code
        res.render('recipe', { submitted: true, Name: 'Recipe Name', Instructions: ['Step 1', 'Step 2'] });
    });
    

    here's the full code how I achieved it -

    EJS template file:

    <body>
        <form action="/Recipes" method="post">
            <input type="text" name="recipeName" placeholder="Enter recipe Name" required>
            <button>Find</button>
        </form>
    
        <% if (submitted) { %>
            <!-- The below code will only run if the form is submitted -->
            <section class="GPT">
                <h1><%= Name %></h1>
    
                <% Instructions.forEach(function(instruction) { %>
                    <ul><%= instruction %></ul>
                <% }); %>
    
                <a href="/"><button>Home</button></a>
            </section>
        <% } %>
    </body>
    

    Server End Code (NodeJS)

    app.use(bodyParser.urlencoded({ extended: true }));
    app.set('view engine', 'ejs');
    
    app.get('/Recipes', (req, res) => {
        // Render the EJS template with submitted set to false (initial page load)
        res.render('recipe', { submitted: false });
    });
    
    app.post('/Recipes', (req, res) => {
        // Process the form submission here
    
        // Set submitted to true to render the specific code
        res.render('recipe', { submitted: true, Name: 'Recipe Name', Instructions: ['Step 1', 'Step 2'] });
    });