Submit a data array using formData through axios

I am planning to send array data using formData. The backend is set up to accept the data array separated by a dash ; For example, if I were to use Postman and input the form-data like this:

id_barang : 122;288;383 (sending 3 values of id with dashes ;)

Would my formData implementation look something like this?

data [
       {
          id_barang : 122
       },
       {
          id_barang : 288
       },
       {
          id_barang : 383
       }
    ]
    
     let barang = data.map(x => x.id_barang).join(";");
     const f = new FormData();
     f.append("id_barang", barang);


     //If there are any mistakes in my approach, please do correct me

This is how my backend processes the data:

id_barang_data := strings.Split(r.FormValue("id_barang"), ";") // This will result in: 1002;983;756
    
for i, _ := range id_barang_data { // Looping through each value one by one
        rSegAnalisaMethodDetail := models.SegAnalisaMethodDetail{}
        id_barang, err := strconv.Atoi(id_barang_data[i])
        if err != nil {
            responses.ERROR(w, http.StatusBadGateway, err)
        }

Answer №1

Your code is correct, but you may have missed adding a way to send your request with axios. When using FormData with axios, make sure to include

'Content-Type': 'multipart/form-data'
. However, if you are not including any files in the FormData, it is not necessary to use it.

Below is the complete action:

var banyakBarang = [
    { id_barang: 122 },
    { id_barang: 288 },
    { id_barang: 383 }
];

var barangString = banyakBarang.map(function(barang) {
    return barang.id_barang;
}).join(';');

var formData = new FormData();
formData.append('id_barang', barangString);

axios({
    method: 'post',
    url: '/x',
    data: formData,
    headers: {
        'Content-Type': 'multipart/form-data'
    },
});

Request Payload:

id_barang: 122;288;383

Answer №2

One way to handle arrays in a FormData object is by converting the array to a string using JSON.stringify(), appending it to the FormData, and then parsing it on the backend for usage. Here's an example to illustrate this:

let formData = new FormData();

let data = [
       {
          id_barang : 122
       },
       {
          id_barang : 288
       },
       {
          id_barang : 383
       }
    ]
formData.append("arr", JSON.stringify(data));

for (var value of formData.values()) {
   console.log(value);
}

Answer №3

Utilize Axios' paramsSerializer feature by configuring it to use a comma-separated arrayFormat with the qs.stringify method.

const customParamsSerializer = (params: any) => stringify(params, { arrayFormat: 'comma' });

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

Is there a way to implement request-specific global variables for individual websocket connections in a Node.js application, similar to using res.locals for

Currently, I'm working on creating global variables within the io.use method of the socket.io server-side library. The goal is to have variables that are accessible throughout the entire request lifecycle for websockets. My setup involves using the ex ...

Obtaining the current value with each keystroke

While working with vue.js, I'm building a table that contains an input field called quantity. However, when I start typing the first word, it shows 'empty' on the console. If I type 3, it displays empty; and if I type 44, it prints 4. I am ...

Ways to categorize items using JQuery based on their hierarchical structure

I am looking to organize the following HTML content: <h2>State the Issue  </h2> <h3>Provide information about your objective</h3> <h3>Share any error messages received</h3> <h2>Outline Your Attempts  ...

Secure your browsing experience with AngularJS authentication prompt

Currently, I am working on building an application using AngularJS for the front-end and JavaEE for the back-end. In my AngularJS application, I am trying to access a REST resource provided by the back-end which is protected with JAAS authentication, allow ...

"Combining background images with javascript can result in displaying visual elements

Hello! I am in need of assistance with a CSS + Javascript fog effect that I have developed. It is functioning properly on Firefox, Opera, and Chrome but encountering issues on IE and Edge browsers. The effect involves moving two background images within a ...

How can I dynamically redirect based on the selected radio button value in a React application?

I've been attempting to use the "navigate" method from "react-router-dom" to redirect users from the Login screen based on the radio button they click. I've tried using states, but I'm unsure if that's the best approach or if there&apos ...

What strategies can I employ to speed up the slow build times in next.js?

Having thoroughly explored the Next JS documentation and delved into related inquiries like Slow page build time in development with Next.js and TypeScript (although that pertains to TypeScript specifically - this concern revolves around JavaScript without ...

Dialogue Inventory System

I am in the process of developing a conversation system that includes a page where users can view all of their conversations and select which one they want to reply to. The layout is structured as follows: You can view an image of the layout here. The co ...

Can a string or javascript object be uploaded without being saved in a file? - IPFS

I've been exploring the capabilities of js-ipfs API and I'm curious to know if js-ipfs is limited to only uploading files/folders. Is there a way to upload other types of data, such as a JavaScript object like: { heading:"SomeHeading", c ...

Associating information with a dropdown menu

My goal is to bind a drop-down using a global variable (the array name). The binding works correctly here: Click here - dropdown is populating fine var name = ['us', 'china', 'kenya', 'us', 'china', &ap ...

Obtain a report using a variety of different conditions

My database has a table with the following fields: TPI CLICKS IMPRESSION CLASSIFY I am looking to retrieve 3 specific results: 1) Calculate SUM(CLICKS)/SUM(IMPRESSION) * 100 GROUPED BY TPI 2) Calculate SUM(IMPRESSION) WHERE CLASSIFY = "XYZ" GROUPED BY ...

Integrate the perfect-scrollbar jQuery plugin into RequireJS

Recently, I decided to explore RequireJS for my projects but I am still trying to understand its functionalities. I'm currently attempting to incorporate perfect-scrollbar, specifically the jQuery version, into my work. Here's a snippet from my ...

Encountering difficulties with image processing on a web page

Recently, I've been experimenting with uploading an image and converting it to a grayscale version on my webpage. Oddly enough, the javascript code works perfectly when tested locally but fails to generate the grayscale image once integrated onto the ...

Capture the current state of a page in Next.js

As I develop my Next.js application, I've encountered an architectural challenge. I'm looking to switch between routes while maintaining the state of each page so that I can return without losing any data. While initialProps might work for simple ...

Retrieving information from a separate JavaScript file

I'm currently developing a Discord Bot and my code is all contained within one file. My goal now is to break this code up into multiple files for better organization. For instance, I plan to have: index.js which will handle all the requires (e.g. var ...

Is there a way to create an internal link to another HTML templating engine page within Express.js?

I am currently facing an issue with two Pug files, index.pug and search.pug, stored in a /views folder. In my index.pug file, I have the following line of code: a(href="/search.pug") Search In my JavaScript file, I have specified the view engine as P ...

Submit your document using the connect-form tool

I ran into an issue while trying to upload a file using connect-form. I found that in order to successfully upload the file, I had to disable the bodyParser() function in my app.js. If I kept bodyParser() enabled, it would result in an error: loading forev ...

:Incorporating active hyperlinks through javascript

Hey there, I've encountered a little conundrum. I have a header.php file that contains all the header information - navigation and logo. It's super convenient because I can include this file on all my pages where needed, making editing a breeze. ...

Using ReactJS and react-router to exclude the navigation menu on the login page

I have a LoginPage designed like this: https://i.sstatic.net/yzovV.png After logging in, you will be directed to this page: https://i.sstatic.net/pZFou.png Now, I want the login page to have no navigation and look like this: https://i.sstatic.net/1sH9v ...

Dynamic class name changes in Angular.js based on JSON object

I am trying to dynamically change the class of an <li> element based on the category value I am getting, but for some reason the class name won't update. Here is the code snippet: <div id="content"> <ul id="container" ng-controller ...