Send information as FormData object

I'm getting the data in this format:

pert_submit: {systemId: "53183", pert-id: "176061", score: 0, q2c: "3\0", q2t: "", …}

Now I need to send it as FormData in my post request. Since I can't use an HTML form for this purpose, the data should be in the following format in the http post call

systemId: "53183", pert-id: "176061", score: 0, q2c: "3\0", q2t: ""

I attempted to use FormData like this

 var form_data = new FormData();
            for ( var key in this.dataObject['pert_submit'] ) {
                form_data.append(key, this.dataObject['pert_submit'][key]);
            }

How can I achieve sending FormData in the specified format as mentioned above

(systemId: "53183", pert-id: "176061", score: 0, q2c: "3\0", q2t: "")

Answer №1

When I need both the key and value from an object, I prefer using Object.entries over Object.keys. One neat trick is to use array destructuring within a .forEach loop to easily access both values.

const data = {systemId: "53183", "pert-id": "176061", score: 0, q2c: "3\0", q2t: "" };
const formData = new FormData();

Object.entries(data).forEach(([key, value]) => formData.append(key, value))

console.log([...formData.entries()]);

Answer №2

Dealt with technicians who struggle to adapt; as highlighted in the feedback, manually creating the string is necessary. Here's a solution.

Keep in mind that when adding to FormData, a key is needed. In this example, I used "pert_submit"; you'll have to determine the appropriate key with the tech team. You could also consider sending data directly to the request body using fetch or XMLHttpRequest, which can be more complex.

const data = { systemId: "53183", "pert-id": "176061", score: 0, q2c: "3\0", q2t: "" };
const getStringIfString = (val) => JSON.stringify(val);
const formattedOutput = Object.entries(data).reduce((agg, [key, val]) => `${agg}${agg.length ? ', ' : ''}${key}: ${getStringIfString(val)}`, "");
const formData = new FormData();
formData.append('pert_submit', formattedOutput);
console.log(formattedOutput);

Lastly, note that the value "3\0" is interpreted in JavaScript as the number 3 followed by a NUL character, explaining any unusual output in the log.

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

Subscribing to valueChanges in reactive forms to dynamically update checkbox options

My goal is to create a select dropdown with options for bmw, audi, and opel. The user can only select one option from the dropdown, but they should also have the ability to select the options that were not chosen using checkboxes. cars = [ { id: 1, na ...

Responsive screen sizing in Vue.js

https://i.stack.imgur.com/8qwpn.png I added a margin-left to my component due to it being blocked by the side-bar and the "Roles" table. Is there a way to shift my table to the right when the screen width is less than 992? I need it to be responsive acro ...

Chrome fails the karma tests while phantomjs passes them

I've been struggling with this issue for some time now and can't seem to find a solution. I'm working on an Ionic 2 project that utilizes Angular 2's testing environment. When I run 'ng test' using Karma's Chrome launcher ...

Tips for creating a dynamic sidebar animation

I have recently delved into the world of web design and am eager to incorporate a sidebar into my project. While browsing through w3school, I came across a design that caught my eye, but I found myself struggling to grasp certain concepts like the 'a& ...

What is the process for transferring a PDF document to the frontend?

I have a file saved in .PDF format on my computer, and I am attempting to send it to the frontend using node/express. Although I am able to successfully send the file as a binary string stream to the frontend, when trying to download the .PDF onto the use ...

What are the best techniques for maintaining state in Xstate state machines within a React application?

I'm currently using a functioning cart state machine in reactjs to add items to the cart. However, I've noticed that when refreshing the page, the context is not persisted. As someone new to state machines, I would appreciate any assistance in fi ...

Issues with Firebase Cloud Messaging functionality in Angular 10 when in production mode

Error: Issue: The default service worker registration has failed. ServiceWorker script at https://xxxxxx/firebase-messaging-sw.js for scope https://xxxxxxxx/firebase-cloud-messaging-push-scope encountered an error during installation. (messaging/failed-ser ...

AngularJS implemented a header authorization feature

I've been attempting to include an authorization header in my requests, but I'm facing some issues. Here is the code I am using: var config = {headers: { 'Authorization': token } }; return $http.get('http://localhost:3000/api ...

Error message: Issue with AWS Serverless Lambda and Angular - TypeError: express function not defined

I'm encountering an issue when trying to deploy my application from localhost:4200 to AWS serverless Lambda. The error in cloudwatch logs is causing a 500 {"message": "Internal server error"} response when I access the URL. My understanding of AWS is ...

What could be causing the lack of data with 'react-hook-form'?

I have encountered an issue while working with react-native and using 'react-hook-forms' for creating dynamic forms. The problem is that the data object returned is empty, even though it should contain the values entered in the input fields. When ...

Function that is triggered repeatedly when modifying the state within it

Within my render method, I am calling a handlePageClick function like this: onPageChange={this.handlePageClick} The function itself looks like this: handlePageClick = data => { this.setState({ circleloading: true }); let names = ...

Can we dynamically apply a class to the body depending on the domain in the window's URL?

Currently, I am developing a website for a company that has operations in both New Zealand and Australia. They have domains pointed to the same website with both .co.nz and .com.au extensions. I have written the following code to assign the class "austral ...

I am encountering a problem with my Vuex getter where it is sending an Array with a length of 0, but when expanded in the console,

Currently, I'm utilizing Vuex to interact with a Django API in order to fetch count data. state: { DailyCycleDate: [] }, getters: { DailyCycleDate : state => { console.log('Getter') console.log('Length of Array: &apo ...

Troubleshooting Problem with CSS Background-Image in Safari

These questions have been popping up all over the web with little response. I've added some CSS in jQuery like this: $('#object').css('background-image', 'url(../../Content/Images/green-tick.png)'); This works in all b ...

A guide on consolidating all app.use statements into a single shared file

My application's starting point, the index file, contains multiple instances of app.use. For example: app.use( if (!req.contextToken && req.contextTokenchecked) { req.queryToFirebase = false; req.contextTokenchecked = tru ...

What is the best way to split a single column into two using blocks?

I am working with a container that currently has all its blocks lined up in a column. I need to divide them into two columns, with 5 blocks in each. Unfortunately, the plugin I am using generates the code for me and does not allow me to insert my own div e ...

Unexpected updates occurring in custom Google Sheet functions

Currently, I am utilizing a personalized function to retrieve price data for EVE Online. However, I am encountering an issue where the function is updating every 10-20 minutes, leading to a depletion of my daily URL Fetches quota. The primary function can ...

Can theme changes be carried over between different pages using Material UI?

I've encountered an issue with MUI 5.14.1 where I'm getting an error every time I attempt to save themes across pages using localStorage. Any suggestions on how to resolve this problem or recommendations on a different approach would be greatly a ...

There is an issue as headers cannot be changed after being set for the client

I am in the process of developing an employee leave management system. Everything runs smoothly until an issue arises when attempting to update the leave status as an admin, and the logged-in account or user does not have admin privileges. There is a midd ...

Buefy table in Vue with various row statuses

One interesting feature of Buefy tables is the ability to highlight rows with a specific color based on a variable in the row. :row-class="(row, index) => row.variable === x && 'is-info'"> In order to style the specific row class: <styl ...