JS AJAX Request Content-Type Issues (using formData object)

Say I have a simple HTML5 Form:

<form id="userForm" method="POST" action="checkvalue.php">
  <label for="userValue">Enter a value</label><br />
  <input id="formValue" type="number" name="userValue" min="1" max="3500" placeholder="(e.g. 23)" pattern="(\d){1,4}" required><br />
  <input type="submit" value="Check Value">
<p id="responseArea"></p>

And a simple XMLHttpRequest:

  • Notice setRequestHeader(‘Content-Type’… commented out

And a simple PHP response function (checkvalue.php):

  function check_value($value) {
    if(is_numeric($value)) {
      $value = (int)$value;
      echo $value;
    } else {
      echo 'false';

So if I use the default Content-Type (multipart/form-data) this example works as intended (the value entered by the user is sent to checkvalue.php via a POST, that value comes back and is printed onto the page), however many people recommend setting the Content-Type manually to “application/x-www-form-urlencoded”.

When I do manually set the Content-Type to “urlencoded” the PHP file has trouble parsing the POST data and when I call $_POST[‘userValue’] it throws an undefined index.

What is going on under the hood with JavaScript here? I’m curious as to why the POST data is suddenly a giant ball of text for my key=>value pair:

['-----------------------------117412652625677 Content-Disposition:_form-data;_name'] =>


Is there some more formatting that needs to take place client-side that I’m missing?

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