Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fallback for FormData in IE 8/9

FormData does not exist in IE 8/9 but I need that functionality in those browsers. Is there a nice fallback for this?

I would try to send over json data, but I need to pass over a file to the server. I append this file to the formData in modern browsers and just submit an XHR request. Because FormData does not exist in IE 8/9 this obviously fails.

// I cant seem to get this to work with a file. $.ajax({     url: '/genericHandlers/UploadDocsFile.ashx',     type: "POST",     data: model.toJSON(),     contentType: 'application/json'     }).done(function  (data) {         log('stuff happened!');     }); 

Maybe an alternative is to create a fake form object in js then append the data to that?

like image 659
Mike Fielden Avatar asked Jun 01 '12 14:06

Mike Fielden


2 Answers

I know only one possible solution, but it's not really 1-1 fallback for IEs. There are no possible communication API for sending files, because you cannot bind input fields in old browsers, like in a modern ones using FormData. But you can send whole form using an iframe. For this case you can use jquery.form plugin that support XHR DataForm and iframe (data sends with iframe when browser do not FormData API support).

like image 84
Dmitry Polushkin Avatar answered Sep 17 '22 17:09

Dmitry Polushkin


You can send the file manually using XMLHttpRequests, there is lots of information on this here.

You could test if the browser can use the FormData object first with:

if(typeof FormData !== 'undefined')    ... 

MDN has a this function which you could modify for the fallback:

var XHR = new XMLHttpRequest(); var urlEncodedData = ""; var urlEncodedDataPairs = []; var name;  // We turn the data object into an array of URL encoded key value pairs. for(name in data) {   urlEncodedDataPairs.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name])); }  // We combine the pairs into a single string and replace all encoded spaces to  // the plus character to match the behaviour of the web browser form submit. urlEncodedData = urlEncodedDataPairs.join('&').replace(/%20/g, '+'); 
like image 39
99 Problems - Syntax ain't one Avatar answered Sep 17 '22 17:09

99 Problems - Syntax ain't one