Error in Express.js application: form fields lose their values

I am currently developing a blogging application using Express, EJS and MongoDB.

One of the main features is an "Add New Post" form with an addPost() method in the controller;

exports.addPost = (req, res, next) => {
    const errors = validationResult(req);
    const post = new Post();

    post.title = req.body.title;
    post.short_description = req.body.excerpt
    post.full_text = req.body.body;

    console.log(post);

    if (!errors.isEmpty()) {
        req.flash('danger', errors.array());
        req.session.save(() => res.render('admin/addpost', {
            layout: 'admin/layout',
            website_name: 'MEAN Blog',
            page_heading: 'Dashboard',
            page_subheading: 'Add New Post',
            post: post
        }));
    } else {
        post.save(function(err) {
            if (err) {
                console.log(err);
                return;
            } else {
                req.flash('success', "The post was successfully added");
                req.session.save(() => res.redirect('/dashboard'));
            }
        });
    }
}

The form view:

<form action="./post/add" method="POST" class="mb-0">

    <div class="form-group">
        <input type="text" class="form-control" name="title" value="<%= req.body.title %>" placeholder="Title" />
    </div>

    <div class="form-group">
        <input type="text" class="form-control" name="excerpt" value="<%= req.body.excerpt %>" placeholder="Excerpt" />
    </div>

    <div class="form-group">
        <textarea rows="5" class="form-control" name="body" placeholder="Full text">
            <%= req.body.title%>
        </textarea>
    </div>

    <div class="form-group mb-0">
        <input type="submit" value="Add Post" class="btn btn-block btn-md btn-success">
    </div>

</form>

If certain required fields are filled in but not all, the form does not retain the data when re-rendered. The expected data from the submitted fields should persist even for the empty required fields.

Even though the generated HTML shows the correct values like title and excerpt, the form seems to reset them after submission:

{
  updated_at: 2020-03-18T10:49:17.199Z,
  created_at: 2020-03-18T10:49:17.199Z,
  _id: 5e71fcbe7fafe637d8a2c831,
  title: 'My Great Post',
  short_description: '',
  full_text: ''
}

Here's the link to the image showing this issue: https://i.stack.imgur.com/C1wQz.png

Any insights on what might be causing this behavior?

UPDATE:

This snippet displays the output HTML code of the form with cleared input values even when they were initially filled:

<form action="./post/add" method="POST" class="mb-0">
    <div class="form-group">
        <input type="text" class="form-control" name="title" value="" placeholder="Title">
    </div>

    <div class="form-group">
        <input type="text" class="form-control" name="excerpt" value="" placeholder="Excerpt">
    </div>

    <div class="form-group">
        <textarea rows="5" class="form-control" name="body" placeholder="Full text"></textarea>
    </div>

    <div class="form-group mb-0">
        <input type="submit" value="Add Post" class="btn btn-block btn-md btn-success">
    </div>
</form>

Answer №1

Here are a couple of adjustments you'll need to make in your controller and view. I've outlined the changes below

In your controller

exports.addPost = (req, res, next) => {
    var form = {
        titleholder: req.body.title,
        excerptholder : req.body.excerpt,
        bodyholder: req.body.body
    };
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
            req.flash('danger', errors.array())
            //req.session.save(() => res.redirect('../addpost'));
            res.render('admin/addpost',{
                layout: 'admin/layout',
                website_name: 'MEAN Blog',
                page_heading: 'Dashboard',
                page_subheading: 'Add New Post',
                form:form});
    } else {

The code after 'else' remains the same as what you already have. I've included a new form object and changed your res.redirect to res.render

And here's how your view will look

<div class="col-sm-7 col-md-8 col-lg-9">
    <div class="card">
        <div class="card-header d-flex px-2">
            <h6 class="m-0"><%= page_subheading %></h6>
        </div>
        <div class="card-body p-2">
            <form action="./post/add" method="POST" class="mb-0">               
                <div class="form-group">
                        <input type="text" class="form-control" name="title" value="<%= typeof form!='undefined' ? form.titleholder : '' %>" placeholder="Title" />
                </div>

                <div class="form-group">
                        <input type="text" class="form-control" name="excerpt" value="<%= typeof form!='undefined' ? form.excerptholder : '' %>" placeholder="Excerpt" />
                </div>

                <div class="form-group">
                        <textarea rows="5" class="form-control" name="body" placeholder="Full text"><%= typeof form!='undefined' ? form.bodyholder : '' %></textarea>
                </div>

                <div class="form-group mb-0">
                    <input type="submit" value="Add Post" class="btn btn-block btn-md btn-success">
                </div>
        </form>
  </div>
    </div>
</div>

The values for the value attribute have been updated. I've also submitted a pull request for your github project.

Answer №2

Everything is set up correctly.

<form action="./post/add" method="POST" class="mb-0">
    <div class="form-group">
        <input type="text" class="form-control" name="title" value="<%=post && post.title? post.title : ''%>" placeholder="Title" />
    </div>

    <div class="form-group">
        <input type="text" class="form-control" name="excerpt" value="<%=post && post.short_description? post.short_description : ''%>" placeholder="Excerpt" />
    </div>

    <div class="form-group">
        <textarea rows="5" class="form-control" name="body" placeholder="Full text"><%=post && post.full_text? post.full_text : ''%></textarea>
    </div>

    <div class="form-group mb-0">
        <input type="submit" value="Add Post" class="btn btn-block btn-md btn-success">
    </div>
</form>

Answer №3

Below is the fully functioning code that adds posts:

Within the controller:

exports.addPost = (req, res, next) => {

    var form = {
        titleholder: req.body.title,
        excerptholder: req.body.excerpt,
        bodyholder: req.body.body
    };

    const errors = validationResult(req);

    const post = new Post();
    post.title = req.body.title;
    post.short_description = req.body.excerpt
    post.full_text = req.body.body;

    if (!errors.isEmpty()) {
        req.flash('danger', errors.array())
        res.render('admin/addpost', {
            layout: 'admin/layout',
            website_name: 'MEAN Blog',
            page_heading: 'Dashboard',
            page_subheading: 'Add New Post',
            form: form
        });
    } else {
        post.save(function(err) {
            if (err) {
                console.log(err);
                return;
            } else {
                req.flash('success', "The post was successfully added");
                req.session.save(() => res.redirect('/dashboard'));
            }
        });
    }
}

In the view:

<form action="/dashboard/post/add" method="POST" class="mb-0">
    <div class="form-group">
        <input type="text" class="form-control" name="title" value="<%= typeof form!='undefined' ? form.titleholder : '' %>" placeholder="Title" />
    </div>

    <div class="form-group">
        <input type="text" class="form-control" name="excerpt" value="<%= typeof form!='undefined' ? form.excerptholder : '' %>" placeholder="Excerpt" />
    </div>

    <div class="form-group">
        <textarea rows="5" class="form-control" name="body" placeholder="Full text">
            <%= typeof form!='undefined' ? form.bodyholder : '' %>
        </textarea>
    </div>

    <div class="form-group mb-0">
        <input type="submit" value="Add Post" class="btn btn-block btn-md btn-success">
    </div>
</form>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can React-Select be utilized in the browser directly from the CDN?

Is it possible to utilize react-select directly in the browser without using bundlers nowadays? The most recent version that I could find which supports this is 2.1.2: How to import from React-Select CDN with React and Babel? In the past, they provided r ...

Maximizing HTML5 Game Performance through requestAnimationFrame Refresh Rate

I am currently working on a HTML5 Canvas and JavaScript game. Initially, the frames per second (fps) are decent, but as the game progresses, the fps starts decreasing. It usually starts at around 45 fps and drops to only 5 fps. Here is my current game loo ...

Creating a customized Axios instance in Typescript can provide more flexibility and control over

I am looking to create an API with a customizable instance using Axios. Ideally, I want to be able to use a basic instance like this: api.get("url")... In addition, I would like to have the flexibility to add dynamic bodies and access them using something ...

Update the content of a div element with the data retrieved through an Ajax response

I am attempting to update the inner HTML of a div after a certain interval. I am receiving the correct response using Ajax, but I am struggling to replace the inner HTML of the selected element with the Ajax response. What could be wrong with my code? HTM ...

Enable automatic playback of HTML5 video with the sound on

I want to add an autoplay video with sound on my website, but I'm running into issues with newer browsers like Chrome, Mozilla, and Safari blocking autoplay if the video doesn't have a 'muted' attribute. Is there a clever HTML or Javas ...

Dealing with AJAX errors consistently in jQuery

Is it possible to efficiently handle 401 errors in AJAX calls and redirect to login.html without repeating the same code over and over again? if (xhr.status === 401) { location.assign('/login.html'); } I am seeking a way to manage these erro ...

Utilizing JSON strings within an onclick function

Hey there, currently I am working on sending an encoded JSON through the onclick attribute. However, I am facing a challenge because the JSON contains strings with a lot of apostrophes and quotes which end up closing the quotes in the onclick attribute. Up ...

Create a complete duplicate of a Django model instance, along with all of its associated

I recently started working on a Django and Python3 project, creating a simple blog to test my skills. Within my project, I have defined two models: class Post(models.Model): post_text = models.TextField() post_likes = models.BigIntegerField() post_ ...

The issue persists with the $slice function in MongoDb

I am attempting to retrieve records using an aggregate function in MongoDB, but I keep encountering the error message stating that the operator $slice is invalid: db.getCollection('test').aggregate( [ { $match: { 'subjectId': &apos ...

The current issue with PassportJS's Facebook strategy is that it is failing to transfer data to the subsequent

I'm struggling with implementing the passport Facebook strategy. Here's my implementation: app.post('/auth/facebook', passport.authorize('facebook-token', {session: false}), socialAuths.fbAuth ); This is the code for ...

The request for http://localhost:3000/insert.js was terminated due to a 404 (Not Found) error

As someone new to web development, I am currently tackling a project where I'm having trouble loading the Javascript file insert.js. The HTML document upload.html resides in the public folder, while the Javascript file is located in the main folder. I ...

A lone function making two separate calls using AJAX

I have a function that includes two Ajax Get calls. Each call has a different function for handling success. function get_power_mgt_settings() { window.mv.do_ajax_call('GET',power_mgt.get_spin_down_url{},'xml',true,show ...

Minimize the visibility of the variable on a larger scale

I have a nodejs app where I define global variables shared across multiple files. For example: //common.js async = requires("async"); isAuthenticated = function() { //... return false; }; //run.js require("common.js"); async.series([function () { i ...

Creating endless scroll feature in Vuetify's Autocomplete component - A comprehensive guide

Having trouble with my Vuetify Autocomplete component and REST API backend. The '/vendors' method requires parameters like limit, page, and name to return JSON with id and name. I managed to implement lazy loading on user input, but now I want i ...

The console is showing the Ajax Get request being logged, but for some reason it is not displaying on the

Could someone please explain why this response isn't displaying on the page? $.ajaxPrefilter( function (options) { if (options.crossDomain && jQuery.support.cors) { var http = (window.location.protocol === 'http:' ? &apos ...

Sharing image using the MEAN stack

While I've found numerous resources online discussing this topic, none of them seem to present a method that resonates with me. My current setup involves a form with multiple inputs that are sent to the server upon clicking a "Submit" button. This da ...

Issue with Mobile Touch Screen Preventing Vertical Scrolling

Currently experiencing difficulties with a div element that is not allowing touch and vertical scroll on mobile devices. Although scrolling works fine with the mouse wheel or arrow keys, it does not respond to touch. Have tested this on various devices and ...

How to choose an option from a dropdown menu using React

In a React application, I am creating a straightforward autocomplete feature. The code is outlined below. index.js import React from 'react'; import { render } from 'react-dom'; import Autocomplete from './Autocomplete'; co ...

Incorrect format for a date in AngularJS

I have a time input field where I am receiving the date and time format 'Thu Jan 01 1970 12:59:00 GMT+0530 (India Standard Time)', but I only want to display the time. Is there an issue with the time picker in AngularJS? Can anyone help me resolv ...

What is the best way to handle the select event for a jQuery UI autocomplete when there are images involved?

Looking for help with creating an autocomplete feature with images on this jsfiddle. Despite trying to capture the event when a user selects an image, it doesn't seem to work properly: $("#input").autocomplete({ //source: tags, so ...