0

I want to translate the jQuery code into plain javascript.

I have this function above.

$.post(
    "/product/getList",
    {
        id: id,
        product_id: product_id.value,
    }
).done(function(data) {
    console.log(data)
});

this will send data as FormData code=test&product=227

I tried with xhr

let xhr = new XMLHttpRequest();
xhr.open("POST", "/product/getList", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
    id: id,
    product_id: product_id.value,
}));

xhr.onload = function() {
    let data = JSON.parse(this.responseText);
    console.log(data)
}

and fetch

fetch("/product/getList", {
    method: "POST",
    headers: {'Content-Type': 'application/json'}, 
    body: JSON.stringify({
        id: id,
        product_id: product_id.value,
    })
}).then(response => {
    console.log(response)
});

but both functions send data as Request Body {"code":"s","product":"227"}

How i can send also FormData via xhr and fetch() ?

---------------------- Updated: ----------------------

This is the FormData when i use $.post()

enter image description here

This is my FormData using

headers: {
  "Content-Type": "application/x-www-form-urlencoded",
},

const formData = new FormData();
formData.append("id", id);
formData.append("product_id", product_id);

enter image description here

and try header

headers: {
  "Content-Type": "application/json",
},

enter image description here

  • Does this answer your question? [How do I post form data with fetch api?](https://stackoverflow.com/questions/46640024/how-do-i-post-form-data-with-fetch-api) – Jan Pfeifer Jan 13 '23 at 11:25
  • Unfortunately not.. i will update my question and post the difference between both FormData –  Jan 13 '23 at 11:49
  • Thats in linked question, create `FormData` object, populate it with data (id and product_id) and then use it in body/send argument. – Jan Pfeifer Jan 13 '23 at 11:56
  • To POST like jQuery above just create FormData object. Dont set content type header, or set it to `application/x-www-form-urlencoded` – Jan Pfeifer Jan 13 '23 at 11:58

1 Answers1

0

You can create the FormData object and fill it with your props.

const formData = new FormData();
formData.append('id', id);
formData.append('product_id', product_id.value);

// and send it

xhr.send(formData);

// OR

fetch("/product/getList", {
    method: "POST",
    body: formData
})

But remember that formData.append(..) adds one more field even if it already exists in formData so you can use formData.set(..) instead to ensure your formData has unique fields only.

You can find some docs on developer.mozilla.org