XMLHttpRequest using FormData Object

Hello,

I have been trying to experiment with different Content-Type headers in the FCC code editor, but it hasn’t been working out. I am guessing that maybe the specific FCC challenge is set up on the server side to only accept application/json types?

Could someone take a look at this practice code and let me know if I am doing this correctly?

<form name='sample'>
  <input type='text' name='name' value='john' />
  <input type='text' name='age' value='38' />
  <input type='text' name='friend' value='doggy' />
</form>
<div id='message'>MESSAGE HERE</div>

<script>
  let myForm = new FormData(document.forms.sample);
  let url = 'http://sampleURL.hello';
  let req = new XMLHttpRequest();
  req.open('POST', url, true);
  req.setRequestHeader('Content-Type', 'multipart/form-data');
  req.onreadystatechange = function() {
    if (req.readyState === 4 && req.status === 201) {
      const res = req.response;
      document.querySelector('#message').textContent = `Hello, my name is ${res.name} and I am ${res.age} years old and my best friend is ${res.friend}!`
    }
  }
  req.send(myForm);
</script>

Apparently you can’t console.log a FormData object, so I’m still unsure as to what it actually looks like. I was just wondering, is this what my sent FormData object will look like?

{name: 'john', age: 38, friend: 'doggy'}

And assuming that the server-side middleware code is set up to return the exact FormData object, am I accessing the properties correctly here?

const res = req.response;
document.querySelector('#message').textContent = `Hello, my name is ${res.name} and I am ${res.age} years old and my best friend is ${res.friend}!`

Oh also one last thing. If my <form> element has an enctype attribute, does that mean I don’t need the Content-Type header when sending the POST request?

Thank you!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.