0

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.

coder
  • 41
  • 2
  • 7

2 Answers2

0
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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • thank you for the reply. i already tried. in postman also giving empty post with form-data – coder Apr 04 '19 at 11:01
0

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>
Dominic
  • 62,658
  • 20
  • 139
  • 163
  • thank you for the reply.it is not related to client side issue but server side. even post man (form-data) i didn't get field values – coder Apr 04 '19 at 11:31
  • @coder try square brackets `r.FormValue["username"]` – Dominic Apr 04 '19 at 13:15
  • invalid operation: r.FormValue["username"] (type func(string) string does not support indexing) – coder Apr 04 '19 at 13:23
  • Ah k, think that was an old version of Go. In devtools Network tab your request is definitely sending those in form data? – Dominic Apr 04 '19 at 13:26