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

The form validation feature is not functioning as expected when integrating mui-places-autocomplete with MUI React

I'm currently working on implementing an autocomplete feature using Google Places API in my project with Material UI React, Redux-Form, Revalidate, and MUI-Places-Autocomplete. Although I've successfully integrated the place lookup functionality, ...

Leveraging the Angular (2) routerLinkActive directive to handle dynamic routes

Although my current approach works, I believe there may be a more efficient way to implement this in Angular. The situation is as follows: Imagine nested, inflected paths like /logos and /logo/:id The markup below functions as intended: <li class ...

The type 'function that takes in a CustomEvent and returns void' cannot be assigned to a parameter of type 'EventListenerOrEventListenerObject'

When I upgraded from TypeScript version 2.5.3 to 2.6.1, my custom event setup started giving me an error. window.addEventListener('OnRewards', (e: CustomEvent) => { // my code here }) [ts] Argument of type '(e: CustomEvent) => ...

Tips for extracting sub values from an object with ExpressJS and MongoDB

I am working with data from MongoDB and need to filter out only the testimonials where isDisplayed is true. Is there a way in ExpressJS & MongoDB to achieve this? This is what I have attempted so far: const getSingleAgent = expressAsync(async (req, res) = ...

Identifying added elements that respond to link hover effects

I've been working on a project where I'm trying to replace the default browser cursor with an SVG one using jQuery. Everything seems to be working smoothly, except for changing the cursor when it hovers over links - nothing I've tried so far ...

Ways to safeguard your API endpoint

Just starting out with Node.js/Express, I'm looking to have my front end retrieve data from an endpoint ('/1') without displaying the JSON data to users when they access that specific endpoint. Any guidance on how to accomplish this would be ...

Can you customize the first element within a span tag using a for loop?

I am having an issue where only the last element in a span is being set within a for loop. The code is functioning correctly, but I want to ensure that the first element is the one set as cust_name. success : function(data) { co ...

How to find the length of an array in Node.js without utilizing JQuery

Is it possible to determine the length of the Dimensions array in nodejs? The array can have 1 or 2 blocks, and I need to write an if condition based on this length. Since this code is inside an AWS-Lambda function, using JQ may not be an option. For exam ...

What is the process for creating a custom Vue 3 element with incorporating styles for child components?

After experimenting with Vue's defineCustomElement() to develop a custom element, I encountered an issue where the child component styles were not being included in the shadow root for some unknown reason. To address this problem, I took a different ...

The issue lies with the Cookies.get function, as the Typescript narrowing feature does not

Struggling with types in TypeScript while trying to parse a cookie item using js-cookie: // the item 'number' contains a javascript number (ex:5) let n:number if(typeof Cookies.get('number')!== 'undefined'){ n = JSON.pars ...

The fitBounds and panToBounds functions in react-google-maps fail to properly adjust the map's size

const Map = withGoogleMap(props => { const { activeMarker, zoom, center, showInfoWindow, products } = props; const [selectedPlace, setSelectedPlace] = useState(null); // Code to iterate through items and adjust map size, center, and zoom to inclu ...

The Jquery Index() method often results in a return value of -

I have developed a function in JavaScript that creates HTML content. Within the test(test1) function, I am checking if test1.Test__c is null and changing the color accordingly. The line ".table-striped > tbody > tr.testcss" is responsible for changin ...

What is the best way to eliminate an object from an array of objects depending on a certain condition?

I have an array of objects structured like so: data = [ { "name":"abc", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa9b9899ba9d979b9396d4999597">[email protected]&l ...

What is the best way to combine a new object with an existing array of objects in JavaScript?

https://i.sstatic.net/QIRzO.png Here is an array that I need to modify by adding the object {"temperature":{"work":30,"home":24}} to the beginning: 0 : {title : "tptp", {"temperature":{"work":30,"home":24}}, lastview:"12-12 21:2"} The code I am using is ...

Is there a directive in AngularJS that allows for binding HTML templates using ng-bind-html

I'm working on a directive that has the ability to use dynamic templates with expressions inside them. The challenge I face is if I use ng-bind-html, the expression won't be evaluated properly. On the other hand, using ng-bin-template results in ...

Issue with automatic form submission

What is the best way to automatically submit my form once the timer runs out and also when the refresh button is clicked? I have encountered an issue where every time I try to refresh the page, it prompts for user confirmation. If I click cancel, it stay ...

Resource loading failure: server indicated resource not found (404) despite request being accepted by backend

Having trouble with my routes on Express. My add product route works perfectly, but the other one is giving me a 404 status on the client side. I logged my req.body and the data was accepted, so I'm confused about what could be causing the issue. Her ...

Using Selenium Webdriver with C# to dynamically expand a RadMenu Webelement in Javascript

I am currently working with Selenium WebDriver in C# and facing an issue with a RadMenu. My goal is to hover over the menu so that it expands a sub menu, where I can find a specific webelement to click. I have tried using JavaScript for this purpose, but u ...

Manipulating video volume using JavaScript injection

My web page includes a video, and I have successfully used JavaScript injection to control the play/pause functionality. Now, I am looking to also adjust the volume based on percentage. How can I create a function that decreases or increases the volume acc ...

Launching Node.js + Express on the server

Trying to Deploy Node.js + Express on Server I'm diving into Node.js and Express development for the first time, and before I fully commit to using these technologies in a new project at work, I want to test them on our server to ensure everything ru ...