point point - 1 year ago 86
Javascript Question

Prevent "new FormData()" in IE from including input elements without a name attribute

I am trying to use jquery ajax to send formData to server...
Here is my html file:

<form id="my_form">
<p>first name :</p>
<input type="text" name="first_name" value="Bill">
<p>second name :</p>
<input type="text" name="second_name" value="Gates">
<p>should not send to the server :</p>
<input type="text" value="haha">

the first and the second input have the 'name' attribute while the last one do not, since I do not want to send this value to the server.The following is my JS file:

var formData = new FormData($('#my_form')[0]);
method : 'POST',
url :'/api/requestUrl',
data : formData,
contentType: false,
processData: false,
success : function() {

Here comes my question,When I run this in IE11, the Request Payload likes the following pictureRequest Payload in IE, and the server says it is a bad content body, so the request failed:

And If I run this in Chrome, it works well,the Request Payload is :
Request Payload in Chrome
I know that if I remove the last input which does not have the 'name' attribute from the Dom, it will work even in IE, So, is there a way to make it work in IE if I remain the last input? thanks a lot...

Answer Source

As far as I can tell, this is indeed an IE bug. One quick workaround is to disable the unnamed input before creating the FormData object.

var $form = $("#my_form");

// Disable "input" elements (input, select, textarea) that do not have 
// a name attribute and were not disabled beforehand, saving a reference to them
var $unnamedInputs = $form.find(":input:not([name]):not(:disabled)").prop('disabled', true);

var formData = new FormData($form[0]);

// Re-enable the inputs that we had just disabled
$unnamedInputs.prop('disabled', false);


Request body in IE11

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download