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()
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);
and try header
headers: {
"Content-Type": "application/json",
},