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

managing, modifying and removing information within the app.controller in AngularJS

I am currently facing a challenge with my Javascript code for a simple web application that involves AngularJS. Here is the snippet of code I am working on: app.filter('startFrom', function () { return function (input, start) { if (i ...

Show segments of video stream on page using node.js

I am currently exploring Node.js and trying to understand how streams work, so please bear with me if I seem a bit unclear. After reading some beginner notes on streams, I decided to test it out. In my project files, specifically in public/images/videos/S ...

React Grid by DevExtreme

Does anyone have a solution for adjusting the fontSize of the TableHeaderRow in a DevExtreme React Grid? Here is some code from a specific website () that I've been exploring: import * as React from 'react'; // Other imports... const Ad ...

Using the Sequelize query string prefix to find data that starts with a specific value

I'm currently working on an autofill feature that takes a string input and provides a list of string suggestions. While using Sequelize's iLike:query, it retrieves all strings in which the queried string is present. However, my goal is to priori ...

In search of a new object value to update

Looking to update the value of a specific object key in an array? Here is the code snippet where I want to make this change. I only want to replace the value under Mon, not the entire array length. The key weekday will be provided dynamically. array = [ ...

How can I pass a string value from C++ to JavaScript in a Windows environment using Visual Studio 2008?

In my current project, I have successfully implemented an IDL for passing a string value from JavaScript to C++. The JavaScript code effectively passes a string value to the C++/COM object. [id(1), helpstring("method DoSomething")] HRESULT DoSomething([in ...

Anchor tags created using JQuery will remain on the same page without redirecting

Presented below is the code I have utilized to construct the anchor tag along with its content. $('div#right-slide').html("<a href=\"http://www.XXXXXXXXXXXX.info/limited-specials/\" ><h1 id=\"specials\">Click Here ...

Should front-end and back-end share Typescript data modeling through classes or interfaces?

I'm currently exploring the best approach to share the same data types between the client (React) and the server (Express + Socket.IO). Within my game, there are various rooms each storing the current status, such as: class GameRoom { players: P ...

Sending various values to a JavaScript function

I am working with a function that looks like this: //Function Call with Single Parameter responses(baseURL); //Function Definition function responses(baseURL) { $.ajax({ url: baseURL, type: "get", cache: false, header ...

Leveraging the arguments object within function declarations

Could someone explain why the foo function functions properly? function foo (x,y) { return arguments.length; } However, when I call the boo function with arguments, it returns an error saying undefined is not a function. function boo (c,d) { return ...

Using Fabric.js to manage image controls situated beneath another overlay image

I'm currently working on a canvas user interface using jquery and the fabric.js library. I managed to add an overlay png image with transparency by implementing the code below: var bgImgSrc = bgImg.attr('src'); canvas.setOverlayImage(bgImgS ...

Google Cloud Endpoints API Encounter 404 Error

Scenario Currently, my setup involves AppEngine Cloud Endpoints using a Bootstrap JavaScript UI along with a Google SQL Datastore. Issue The problem arises when the Javascript tries to call gapi.client.load and receives a 404 error. Surprisingly, the ...

Unable to establish a connection to 'X' as it is not recognized as a valid property

Trying to implement a Tinder-like swiping feature in my Angular project, but encountering an error stating that the property parentSubject is not recognized within my card component. Despite using the @Input() annotation for the property, it still fails to ...

The feature to hide columns in Vue-tables-2 seems to be malfunctioning

The issue I'm facing is with the hiddenColumns option not working as expected. Even when I set it to hiddenColumns:['name'], the name column remains visible. I've updated to the latest version, but the problem persists. UPDATE I am tr ...

Dealing with ReactJs Unhandled Promise Rejection: SyntaxError - Here's the Solution

Struggling to use the Fetch API in ReactJS to retrieve a list of movies. Encountering an issue, can anyone offer assistance? fetch("https://reactnative.dev/movies.json", { mode: "no-cors", // 'cors' by default }) ...

Looking to include some extra padding when an item is displayed - jQuery

So, I'm working on a jQuery code snippet that controls the visibility of a rectangle element: $("#rectangle").hide(); $("#toggle-rec").click(function () { $("#rectangle").toggle(2000); }); This code hides the rectangle initially and toggles it ...

Is it recommended to run JavaScript functions obtained from REST APIs?

Our single page application is built on Angular 4 and we are able to change input fields based on customer requirements. All the business rules for adjusting these fields are coded in JavaScript, which runs on the Java Platform and delivers the output thro ...

"Deleting a specific row from a SQL Server using Node.js: Step-by-Step Guide

Currently, my setup involves using nodeJs as the backend language and sql server as the database. While I have managed to delete whole table rows from the database successfully, I am facing a challenge when it comes to deleting a specific row. Here is the ...

Issue: Proper handling of data serialization from getStaticProps in Next.js

I've been working on Next.js and encountered an issue while trying to access data. Error: Error serializing `.profileData` returned from `getStaticProps` in "/profile/[slug]". Reason: `undefined` cannot be serialized as JSON. Please use `nul ...

Stop the selection of text within rt tags (furigana)

I love incorporating ruby annotation to include furigana above Japanese characters: <ruby><rb>漢</rb><rt>かん</rt></ruby><ruby><rb>字</rb><rt>じ</rt></ruby> However, when attemp ...