3

i will send array data using formData. the backend accepts the data array with a dash ; example if in postman using form-data like this:

id_barang : 122;288;383 (send 3 value id with dash ;)

if i use formData is it 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);


     //please correct me if i'm wrong

my backend

    id_barang_data := strings.Split(r.FormValue("id_barang"), ";") // => 1002;983;756
    
    for i, _ := range id_barang_data { // loop through the files one by one
            rSegAnalisaMethodDetail := models.SegAnalisaMethodDetail{}
            id_barang, err := strconv.Atoi(id_barang_data[i])
            if err != nil {
                responses.ERROR(w, http.StatusBadGateway, err)
            }

4 Answers 4

0

There is nothing wrong with your code. the only thing missing here is that you didn't provide a way of sending your request with axios. when you use FormData with axios you need to add 'Content-Type': 'multipart/form-data'. however if you don't add any files to Formdata then there is no need to use Formdata

Here is the compete 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
Sign up to request clarification or add additional context in comments.

4 Comments

I have used this, sir, but when I post, the data on the backend is not looped or only 1 is entered.. if you use postman the data works everything
You need to split (js) / explode (php) the value. Show your code how you handle it on the backend.
I've updated my question with backend code content :D
I tracked the backend again, it seems there is another form that is not looped causing the 'id_barang' loping to fail, thank you for the answer kang ,,,
0

You can stringify your array and append it in the FormData and in the backend, you can parse that data and use it accordingly. Check out the example below.

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);
}

Comments

0

Axios has paramsSerializer option, you can set it to comma-separated arrayFormat with qs.stringify.

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

Comments

0

A better way you can send an array could be as follows

const arr = [1,2,3,4,5];
const form = new FormData();
arr.forEach(element => {
    form.append('name_of_field[]', element)
});
const result = await axios.post("/admin/groups", form, {
    headers: { 'Content-Type': 'multipart/form-data' }
});

This approach is better because it leverages a widely accepted standard used by web forms and is natively understood by the majority of modern server-side frameworks (e.g., PHP, Express.js with body parsers, Ruby on Rails, Django).

Key reasons for superiority:

  1. Automatic Array Parsing: The server-side framework automatically recognizes the repeated field name ending in [] and converts the incoming values directly into a native array or list data structure. This eliminates the need for manual processing.

  2. Simplified Server Logic: Your backend code receives a ready-to-use array (e.g., [1, 2, 3, 4, 5]), which removes the burden of manual parsing (splitting the string by a delimiter) from the server.

  3. Standard Web Practice: It aligns with the convention for submitting multiple values from HTML forms (like multiple <select> options), making the data handling more conventional and predictable.

In contrast (sending a single delimited string like "122;288;383") forces the backend to manually split that string using the semicolon (or whatever delimiter you choose), which adds an unnecessary step and complexity to the server code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.