XMLHttpRequest POST formData to a new tab

9.3k views Asked by At

Since, loadOneTab() is not available for formData,

  1. How can formData be posted to a new tab?
  2. How can the above new tab foreground/background status be set?

Just a smaple example from Using FormData Objects:

var formData = new FormData();

formData.append("username", "Groucho");
formData.append("accountnum", 123456); // number 123456 is immediately converted to string "123456"

// HTML file input user's choice...
formData.append("userfile", fileInputElement.files[0]);

// JavaScript file-like object...
var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
var blob = new Blob([content], { type: "text/xml"});

formData.append("webmasterfile", blob);

var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);

Clarification:
Normal HTML form with a target="_blank" will POST the form data to a new tab.
Similarly, as mentioned, loadOneTab() can also POST data to a new tab.
Is it possible to do so with XMLHttpRequest?

2

There are 2 answers

3
Blagoh On

XHR has absolutely nothing to do with tabs. If you really want to XHR it, then you should take the returned source and update document of the target tab with it.

Otherwise I would just use loadOneTab: I would think something like this where things are turned into nsIFile:

Import encodeFormData function form here: https://stackoverflow.com/a/25020668/3791822

// HTML file input user's choice...
var userfileNSIFILE = new FileUtils.File(fileInputElement.files[0].path);

// JavaScript file-like object...
var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
var blob = new Blob([content], { type: "text/xml"});

//some code here to write blob to temp folder to make nsifile or do some stream stuff to get an nisfileoutputstream?
var blobNSIFILE = ....;

let postData = encodeFormData({
  "webmasterfile": blobNSIFILE,
  "userfile": userfileNSIFILE,
  "username": "Groucho",
  "accountnum": 123456
}, "iso8859-1");

gBrowser.loadOneTab("http://foo.com/submitform.php", {
  inBackground: false,
  postData: postData
});
0
Blagoh On

This is what I mean by loading responseText of xhr into a tab, can copy paste to scratchpad.

var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        switch (xhr.readyState) {
                case 4:
                   prompt('done', xhr.responseText);
                    gBrowser.loadOneTab('data:text/html, ' + encodeURIComponent(xhr.responseText), {
                      inBackground: false
                    });
            break;
          default:
        }
    };
    xhr.open("GET", "https://www.bing.com/");
    xhr.send();