I have a requirement to download multiple files using POST request. So I am using form submit to get this done.

I have followed two approaches to accomplish this.

1. Create a Form. Fill input details with payload data. Then set the target of the Form to _self then manually submit the Form. But I see few problems with this approach. Like, When payload is incorrect or Server has download API problems the current page will be redirected to 404 page.

var method = "POST";
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", "https://some-url");
appendFormData(form, options.data.items);
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);


2) Second approach is similar to the first one, except that I am creating an iframe, appending it to DOM and providing iframe as the target for Form. This works but the problem is, I am not sure when to remove the iFrame from the DOM.

    var method = "POST";
var iframe = document.createElement("iframe");
iframe.setAttribute("name", "hidden-frame");
iframe.style.display = "none";
document.body.appendChild(iframe);
var iDocument = iframe.contentWindow.document;
var form = iDocument.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", "https://some-url");
form.setAttribute("target", "hidden-frame");
appendFormData(form, options.data.items);
iDocument.body.appendChild(form);
form.submit();


Can you please suggest ways to improve the above solution or suggest if there are any better approach to accomplish the same.

iframe.addEventListener('loadend', function() {

The iframe has many other events (load, error, abort, progress) which might also be useful.
• I tried load and loadend events which are not working. load will be called when iframe is appended to dom but not when form is submitted and loadend is not even triggered(According to mdn loadend will be called only for iframe content and XMLHttpRequest not for form submit) – manikanta deva Apr 13 '17 at 5:17