5

Im trying to post a form data in js :

I have this code :

var formData = new FormData();
  formData.append("username", "Groucho");
  formData.append("accountnum", 123456);
  formData.append("afile", "2");

var xhr = new XMLHttpRequest();
xhr.open("POST", "http://xxxxx/xx.ashx",true);
xhr.send(formData);

Formdata according MDN is not available in IE ( or unknown).

When I try this in FF :

enter image description here ( i think its fine...).

when I try in IE :

enter image description here

What is the solution to post form data ( or my data but in objective way) CROSSBROWSER ?

Nicolas Kaiser
  • 1,628
  • 2
  • 14
  • 26
Royi Namir
  • 144,742
  • 138
  • 468
  • 792

2 Answers2

10

I wrote a simple wrapper that you can use to send FormData in IE (and it won't mess up anything in webkit/gecko either). Simply include the following js before you try to use FormData:

var ieFormData = function ieFormData(){
if(window.FormData == undefined)
{
    this.processData = true;
    this.contentType = 'application/x-www-form-urlencoded';
    this.append = function(name, value) {
        this[name] = value == undefined ? "" : value;
        return true;
    }
}
else
{
    var formdata = new FormData();
    formdata.processData = false;
    formdata.contentType = false;
    return formdata;
}

}

Now simply switch all new FormData() calls to new ieFormData(), and switch

processData: false, 
contentType: false,

to

processData: formdata.processData,
contentType: formdata.contentType,
cache: false,

and you're all set. Of course, this won't allow you to include files (you still need the iframe hack), but it will allow you to mimic FormData in IE.

Sam Grondahl
  • 2,397
  • 2
  • 20
  • 26
  • I have a similar problem but I am unsure how to fix this, what would my code change from if it was var postedFile = document.getElementById("file").files[0]; var formElement = document.getElementById("formID"); var form = new FormData(formElement); form.append('postedFile', postedFile); request.open("POST", "/Admin/SaveQuestion/", true); request.send(form); – Jay Apr 25 '14 at 14:20
  • I am not even too worried about the posted file, I just want to be able to submit the rest of the form data – Jay Apr 25 '14 at 15:15
3

You didn't say which version of IE you're using. The formData object is not supported in IE9 or lower. XMLHTTPRequest2 (which contains the formData object) should be supported in IE10 (http://caniuse.com/xhr2)

Cross-browser AJAX file upload is very hard to do right now. You could try building your own form header/boundaries in Javascript (see answer here: XMLHttpRequest POST multipart/form-data) but, personally, I don't believe it is worth the effort.

Community
  • 1
  • 1
BlueSix
  • 131
  • 2
  • 9