point
point

Reputation: 23

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">
    <div>
        <p>first name :</p>
        <input type="text" name="first_name" value="Bill">
    </div>
    <div>
        <p>second name :</p>
        <input type="text" name="second_name" value="Gates">
    </div>
    <div>
        <p>should not send to the server :</p>
        <input type="text" value="haha">
    </div>
</form>

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]);
            $.ajax({
                       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...

Upvotes: 2

Views: 195

Answers (2)

Fabr&#237;cio Matt&#233;
Fabr&#237;cio Matt&#233;

Reputation: 70169

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);

Fiddle

Request body in IE11

Upvotes: 1

guest271314
guest271314

Reputation: 1

You could clone the original form, remove last input element or input element that does not have name attribute, then set FormData parameter to cloned form where last input would not be included.

var clone = $("#my_form").clone();
clone.find("input:last").remove();
var formData = new FormData(clone[0]);

Upvotes: 0

Related Questions