I'm trying to retrieve data from FormData
js side ajax request
function sendForm()
{
let form=document.getElementById("myForm");
var formData = new FormData();
for(var i=0; i<form.length; i++)
{
formData.append(form[i].name, form[i].value);
}
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
console.log(xmlHttp.responseText)
}
}
xmlHttp.open("post", url);
xmlHttp.setRequestHeader("Content-Type", "multipart/form-data");
xmlHttp.send(formData);
}
from Go side
func login(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
username:= r.FormValue("username") // Data from the form
password:= r.FormValue("password")
fmt.Println(username,password) //getting empty
}
I have also tried in postman with form-data option but getting same result but in php it is working fine... in Go lang ,i dont't know how to handle multipart/form-data.
xmlHttp.setRequestHeader("Content-Type", "multipart/form-data");
Normally, XMLHttpRequest will read the FormData object and generate the Content-Type header from it.
Here, you are overriding that by setting the Content-Type explicitly, but you are missing the mandatory boundary
parameter so the multipart body can't be decoded.
Remove the quoted line.
Works fine for me, check the network/response. I suggest you use fetch
as it's simpler.
function onSubmit(e) {
e.preventDefault();
const data = new FormData(e.target);
fetch('https://httpbin.org/post', {
method: 'post',
body: data,
})
.then(r => r.json())
.then(r => console.log(r))
}
document.querySelector('form').addEventListener('submit', onSubmit);
<form class="form">
<input type="text" name="name" placeholder="Name" />
<input type="email" name="email" placeholder="Email" />
<button type="submit">Submit</button>
</form>
</div>