Manage SPA forms using Dataform Javascript - Safeguarding form information by avoiding inclusion in the URL

I have been using express, mongoose, and JavaScript to build a single page application. Everything seems to be working fine, except for one thing - I do not want the form data to show up in the URL when making a post request. I attempted to use a redirect, but it seemed to cause an infinite loop.

Since this is a SPA, I am avoiding using the form method="post" as it would result in a page redirection. My goal is to avoid displaying or redirecting from the URL with query information.

http://localhost:2000/?firstName=John&lastName=James&age=40

This is the structure of the form (index.html) --

<form id="formId">
      <input type="text" name="firstName">
      <input type="text" name="lastName">
      <input type="text" name="age">
      <button type="submit" onclick="processForm(event)">Save</button>
</form>

Below is the JavaScript code for handling the form :

function processForm(event){
  var formData = new FormData(document.forms[0])
  const queryString = Object.fromEntries(
    Array.from(formData.keys()).map(key => [
    key, formData.getAll(key).length > 1 ?
    formData.getAll(key) : formData.get(key)]));
  postData(queryString);   
}

async function postData(data) {
  fetch('/people', {
    method: 'POST', 
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify(data),
  })
  .then(response =>response.json())
  .then(data => console.log('Success:', data))
  .catch((error) => {
  console.error('Error:', error);
  });
};

Answer №1

To successfully handle the form in this SPA application with AJAX, it is essential to prevent the default form submission behavior, which typically leads to a page redirection.

You can achieve this by utilizing the event.preventDefault() method.

Your code structure should reflect the following:

function processForm(event){
  event.preventDefault();
  ...additional form handling logic
}

Moreover, opting for the form.onsubmit event instead of button.onclick event is advisable for data transmission purposes.

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

JWT triggers a JsonWebTokenError with the message "token is not valid"

I implemented token verification in my Node Application using jsonwebtoken. The issue I'm facing is that while jwt.sign works perfectly, jwt.verify is throwing the following error: "auth": false, "message": { "name": "JsonWebTokenEr ...

Angular not firing slide.bs.carousel or slid.bs.carousel event for Bootstrap carousel

I've searched high and low with no success. I'm attempting to detect when the carousel transitions to a new slide, whether it's automatically or by user click. Despite my numerous attempts, I have been unable to make this event trigger. I ha ...

After AngularJS has loaded, CSS animations seem to be ineffective

When loading a page, I have created a div that is displayed. Here is the code: <div ng-show="load" class="rb-animate-time rb-animate-hide rb-load"> <div class="text">Hello world</div> </div> <div ng-init="load = false">&l ...

Selecting middleware to be executed based on Express JS request parameters

Can someone please advise me on how to select between two distinct middleware functions, based on the request for a specific endpoint? It may involve something along these lines: router.post("/findAvailableAgents", chooseMiddleware(middleware1, ...

How come I am unable to terminate this Angular HTTP request?

I've been trying to implement a solution for canceling HTTP requests in AngularJS by referring to this Stack Overflow post. Here's the code snippet I'm using: var canceller = $q.defer(); $timeout(function() { canceller.resolve(); alert ...

How can you access a function from within another function in the same object while keeping the object structure largely intact?

Seeking a solution using JavaScript (ES6), I am in need of referencing a handler function called onKeyup. This will allow me to both add and remove an event listener in two functions that are declared within the same object. Can you suggest how I can acce ...

What is the best way to ensure that the same information is included on every page of

Currently developing a dynamic website where certain components such as the fixed header, menubar, and footer are common across multiple pages. What is the best way to include these fixed components on every webpage? I am utilizing JSP and JavaScript for ...

Optimizing File Transfers and Streaming Using Next.js and CDN Integration

As I work on developing a download system for large files on my website using Next.js and hosting the files on a CDN, I face the challenge of downloading multiple files from the CDN, creating a zip archive, and sending it to the client. Currently, I have i ...

Is there a way to activate the width styling from one class to another?

I have these 2 elements in my webpage: //1st object <span class="ui-slider-handle" tabindex="0" style="left: 15.3153%;"></span> //2nd object <div id="waveform"> <wave style="display: block; position: relative; user-select: none; he ...

Connect jQuery navigation button to a specific web address

Check out this cool jQuery menu script I found: <script type="text/javascript> jQuery(document).ready(function(){ jQuery('#promo').pieMenu({icon : [ { path : "/wp-content/t ...

Configuring environment variables during Jest execution

A variable is defined in my `main.ts` file like this: const mockMode = process.env.MOCK_MODE; When I create a test and set the variable to true, it doesn't reflect as `'true'` in the main file, but as `'false'` instead. describe ...

Tips for tidying up the AppModule in Angular2

After following online tutorials, I managed to create a functional SPA data entry application, although it's just 'ok'. The connection to my WEB API is working fine, but as I've only built out one Model, my AppModule is already quite l ...

What steps do I need to take to containerize my application with a Single Page Application (

I have a dotnet application serving an SPA inside. It is located within a directory named client. To run the application on my local machine, I typically follow these 2 steps: Within the client folder, I execute the following command: npm run build In the ...

Is there a way to identify the source of a div's scrolling behavior?

While working on a complex web page that involves multiple JQuery Dialogs and other widgets, I encountered a frustrating issue. Some of the dialogs contain divs with scrolling abilities (using overflow-y with a fixed height). Whenever I click on one dialog ...

My React application did not display properly after deploying it on GitHub Pages

I attempted to deploy my React app on GitHub Pages, but unfortunately it did not work as expected. When I tried to access the link, all I got was a blank page. Can anyone help me with a solution? Your assistance is much appreciated! Here's a snippet ...

Is it possible to apply CSS based on a component's displayName?

Are you a CSS pro? I'm attempting to apply a class that will make all descendants of an element read-only, but for some reason the style isn't being applied as expected: #ComponentDisplayName * { -webkit-user-select: text; -moz-user-sel ...

The dilemma between installing Electron or installing Electron-Builder: which one

When it comes to installing Electron for an Electron app with React, the method can vary depending on the tutorial. Some tutorials use electron-builder while others do not, but there is little explanation as to why. First: npx create-react-app app cd app ...

Scrollbar in an HTML selection tag

Is there a way to add a scroll bar to an HTML select box without using JavaScript? Alternatively, is there a JavaScript library that can achieve this behavior? Also, I'm looking for a redesign of the interface where I have two select boxes and items ...

Using Mongoose with Next.js Middleware

Currently, I'm attempting to establish a connection between my next.js app and MongoDB using mongoose within the _middeware file located at ./pages/_middleware.ts. However, every time an incoming request is made, I encounter the following error: Erro ...

The proper way to retrieve data using getServerSideProps

Encountering an issue with Next.js: Upon reaching pages/users, the following error is displayed: ./node_modules/mongodb/lib/cmap/auth/gssapi.js:4:0 Module not found: Can't resolve 'dns' Import trace for requested module: ./node_modules/mon ...