Resetting form fields once data has been successfully posted to MongoDB

I have successfully set up a form that sends data to a MongoDB database. However, I am facing an issue with refreshing the input fields after the form is submitted without reloading the entire page.

After calling the resetBooks() function, it seems like it clears the form before posting the data. Is this the correct behavior?

How can I ensure that the form posts the data first and then clears the input fields afterwards?

<div class="booksInput">
  <h4>Add a book</h4>

  <form id="bookForm" method="post" action="/books" 
      target="hiddenFrame" onsubmit="resetBooks()">
       <input class="form-control" name="title" type="text" placeholder="Enter book title">
       <input class="form-control" name="author" type="text" placeholder="Enter author">
       <input class="form-control" name="description" type="text" placeholder="Enter short description">
       <button class="btn btn-primary" type="submit" value="Add Book">Submit</button>
  </form>

</div>

<script>
  function resetBooks(){
    document.getElementById('bookForm').reset();
    };

  app.post("/", (req, res)=>{
  let myBook = new Book (req.body);
  myBook.save()
  .then(item =>{
    res.send("Book saved to database");
  })
  .catch(err=>{
    res.status(err).send("unable to save to database");
   });
  });

</script>

Answer №1

To ensure compatibility with most modern browsers, adding an arbitrary time offset should do the trick. In the past, only Chrome had issues with this, but now Firefox is also affected. With the new Edge browser being Chromium-based, similar issues may arise if things are not offset properly.

I have included some screenshots of Firefox's requests as using fiddles for form submissions can be cumbersome.

function resetBooks(){
    setTimeout(function(){ document.getElementById('bookForm').reset();}, 100);    
};

https://i.sstatic.net/0yHJx.png

https://i.sstatic.net/OhuZY.png

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

What is the reason behind getting `[Object object] [ Object object]` when you perform `{} + {}` in JavaScript?

I am just starting to learn JS and I'm puzzled by a situation. Let's consider the following code snippet: var ids = [10,20,30]; var types= ['PIZZA','HAMBURGER','AVOCADO']; var payload=[]; for(let i = 0; i <= ids. ...

Generate an array that can be accessed across all components

As someone new to reactjs, I'm trying to figure out how to handle an array of objects so that it can be global and accessed from multiple components. Should I create another class and import it for this purpose? In Angular, I would typically create a ...

When a link is added, the Bootstrap drop-down button may become unresponsive

I've encountered an issue with a Bootstrap dropdown menu that I created using jQuery and Bootstrap. The links within the dropdown menu are not redirecting to the correct pages as intended. Can someone help me identify what mistake I might be making he ...

Dynamic backdrop featuring engaging content

I am currently working on a WordPress website that features a dynamic background. While I have successfully implemented movement to the background, the content on the site remains static and unaffected by scrolling. The background does not move alongside t ...

What is the process for performing a kill operation in pymongo?

myclient = pymongo.MongoClient("mongodb://test:example@example.com:27017/admin") myclient.admin.command(killOp(1234)) ?? I'm struggling to locate the correct grammar. ...

Order files by ID during upload using Jquery file upload with blueimp

Incorporating the blueimp jQuery files upload pluginblueimp into my project has been a great help. However, I encountered an issue where the uploaded multiple files do not sort automatically by file name upon refreshing the page. I attempted to modify inde ...

Error: Tried to import a module but encountered a TypeError stating that it cannot read properties of undefined while trying to read 'utf16le'

Attempting to conduct a Jest test on a React component that involves importing a module called "Siwe," which facilitates signing in with Ethereum. The configuration for Jest appears as follows: module.exports = { moduleNameMapper: { "module_nam ...

What is the process for saving information to a database with JavaScript?

I am currently utilizing the Google Maps API for address translation, primarily through the use of a geocoder. I am interested in saving these results to a local database for future reference, as there are limitations on the total number and frequency of ...

How can I use MongoDB's aggregate feature to group objects based on common fields within an array?

Struggling to implement MongoDB aggregate in my project to group the data. Looking for a more efficient approach but unable to find one. { "_id" : ObjectId("5e9a21868ed974259c0da402"), "shopId" : "5e975cc7be7c1b546b7abb17", "shopType" : "Medi ...

The value is undefined until a new Resource object is pushed with the item

I've encountered an issue while testing a factory and I can't seem to find anyone else with the same problem. Can someone help me figure out what's causing this strange error? TypeError: 'undefined' is not a function (evaluating & ...

Working with masonry does not involve filling tiny crevices

Check out the DEMO here Experience the FULL Screen DEMO An issue with Masonry: it's not filling small gaps even when there is available space. For example, in a main container with a width of 896px; next to the first container with an orange backgr ...

Insert a div element into the JavaScript file

I have a JavaScript code snippet that needs to be inserted after the "Artwork" section. Here is the code: <div class="image-upload"> <label for="files"> <img src="ohtupload.jpg"> </label> </di ...

Using Vue for Firestore pagination

Utilizing the bootstrap-vue pagination component: <b-pagination v-model="currentPage" :total-rows="rows" :per-page="perPage" ></b-pagination> Component.vue: export default class PaginatedLinks extends Vue { public currentPage: number ...

Automatically execute a function every 5 seconds in Angular application

I have a component in Angular that is responsible for fetching data from the backend. Below is the code snippet of the component export class MessagesComponent implements OnInit { constructor(private _router: Router, private http: HttpClient) { } t ...

What steps can be taken to resolve the issue of the Cannot POST /index.html error?

Here is an example of a calculator app created using HTML and Javascript. Upon running the program with nodemon and accessing localhost:3000, pressing the submit button triggers an error on Google Chrome. [nodemon] starting `node calculator.js` Server sta ...

Is it necessary to validate, sanitize, or escape data before utilizing the build method in sequelize.js?

I currently have a node/express/sequelize application where I am utilizing the build method in sequelize to generate instances of my foo model. Foo Controller exports.create = function(req, res) { var foo = db.Foo.build(req.body); foo.save().t ...

Autoselecting Dropdown Field on Wordpress Contact Form 7 Depending on Referral URL

I have been referencing the following two answers: Wordpress Contact Form 7 dynamically select dropdown field based on url Auto-select fields in Contact form 7 based on referral link The code snippet below is currently inserted in the CSS block on the / ...

TypeScript Compile Error: The property is not available in the 'IStateParamsService' type

My client project heavily utilizes TypeScript. Currently, I am encountering a technical issue. Within my HTML code, I have an anchor tag as shown below: <a class="btn btn-default mrm" ui-sref="course-detail({courseId: '{{c.Id}}'})">Detail ...

Error: No targets with the name "taskname" were found for the custom Grunt task

Just recently, I decided to create my own custom task and here's the process: Started by making an empty folder named "custom-tasks" in the Document Root Next, I created the actual task file: "mytask.js" Implemented the functionality required for th ...

How to retrieve a variable from an object within an array using AngularJS code

I recently started learning TypeScript and AngularJS, and I've created a new class like the following: [*.ts] export class Test{ test: string; constructor(foo: string){ this.test = foo; } } Now, I want to create multiple in ...