0

am very new to ajax. and currently learning how it works!

so created a new instance of FormData while passing it my form. then i went through the basic ajax rituals: opened a request, set the request header, then send data.

but still i got a very weird response when i tried viewing the $_POST array in PHP with var_dump.

// HTML FORM

  <form id="myForm" action="ajax_response.php" method="post">
    <input type="text" name="name">
    <button type="submit">submit</button>
  </form>

// JAVASCRIPT AJAX

var req = new XMLHttpRequest();
var fData = new FormData(myForm);

req.open('post','ajax_response.php',true);
req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
req.send(fData);
req.onload = function() {
  document.write(this.responsText);
};

// PHP

if(isset($_POST)) {
  var_dump($_POST);
}

// RESPONSE 

 array (size=1)
   '------WebKitFormBoundaryAzMVL1V93W6RKYOA
 Content-Disposition:_form-data;_name' => string '"name"

 test
 ------WebKitFormBoundaryAzMVL1V93W6RKYOA--

' i later got a desire response by commenting out the req.setRequestHeader line.

array (size=1)
  'name' => string 'test'

but i'll like for somebody to please explain to me why i can't send FormData over a Content-Type: application/x-www-form-urlencoded header.

twist
  • 103
  • 8

0 Answers0