Skip to content

Instantly share code, notes, and snippets.

@wycliffepeart
Last active June 27, 2016 20:18
Show Gist options
  • Save wycliffepeart/dec07bab71b9a2129388613bd86fa5cd to your computer and use it in GitHub Desktop.
Save wycliffepeart/dec07bab71b9a2129388613bd86fa5cd to your computer and use it in GitHub Desktop.
Javascript Sending form data using iframe
"use strict";
document.getElementById("file-upload-form").addEventListener("submit", (e) => {
e.preventDefault();
this.inputElement = [];
this.iframeName = "uploader-facade";
this.form = document.createElement("form");
this.iframe = document.createElement("iframe");
this.iframeElement = document.getElementById(this.iframeName);
this.formAttributes = {
target: this.iframeName,
action: "upload.php",
method: "POST",
enctype: "multipart/form-data"
};
// Let's append the iFrame used to send our data
this.iframe.name = this.iframeName;
this.iframe.id = this.iframeName;
this.iframe.style.display = "block";// change to none to hide iframe
if (this.iframeElement)
document.body.removeChild(this.iframeElement);
document.body.appendChild(this.iframe);
// fire when iframe finish load
let onLoad = (e) => {
var iframeDocument = e.target.contentDocument || e.target.contentWindow.document;
console.log("Json Document: ", JSON.parse(iframeDocument.body.innerHTML));
};
// Add load listener to iframe
this.iframe.addEventListener("load", onLoad);
// target all form input elements of type file from the event,
for (let i = 0; i < e.target.elements.length; i++) {
if (e.target.elements[i].nodeName === "INPUT" && e.target.elements[i].type === "file") {
this.inputElement[i] = e.target.elements[i].cloneNode(true);
this.inputElement[i].files = e.target.elements[i].files;
this.form.appendChild(this.inputElement[i]);
}
}
// Set form all attributes
for (let attribute in this.formAttributes) {
if (this.formAttributes.hasOwnProperty(attribute))
this.form.setAttribute(attribute, this.formAttributes[attribute]);
}
// Submit form
this.form.submit();
return this;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment