I would suggest creating an invisible form in your HTML like this:

<form id="invisible_form" action="new_window.php" method="post" target="_blank">
  <input id="new_window_parameter_1" name="parameter" type="hidden" value="default">
</form>

..and then submitting it via jQuery:

$('#new_window_parameter_1').val('value');
$('#invisible_form').submit();
Answer from M. Cypher on Stack Overflow
Top answer
1 of 1
12

If you just want a link that opens a POST-requested page in a new window here are some ideas. However, be aware a POST request can't be bookmarked.

  • You can make a button that opens a POST-requested page in a new window.

    <form method="post" action="http://example.com/example.php"
      target="_blank">
    <input type="hidden" name="name1" value="value1">
    <input type="hidden" name="name2" value="value2">
    <input type="submit" value="Open results in a new window"> 
    </form>
    
  • If you want it to look like a link, you can make a link with an onClick attribute that submits the form.

    <form name="myform" method="post" action="http://example.com/example.php"
      target="_blank">
    <input type="hidden" name="name1" value="value1">
    <input type="hidden" name="name2" value="value2">
    </form>
    
    <a href="http://example.com/example.php"
      onClick="document.forms['myform'].submit(); return false;">Open results
      in a new window</a>
    

    The onClick part submits the form, which opens the POST-requested page in a new window. The return false prevents the browser from also going to the href address in the current window at the same time. If Javascript is disabled or the link is bookmarked, the href address is used as a fallback, but the resulting page won't receive any POST values. This might be confusing or unfriendly for your users if they bookmark the link.

If you want the link to be bookmarkable, investigate if your page can accept GET parameters. If so, then you can make a bookmarkable link.

 <a href="http://example.com/example.php?name1=value1&name2=value2"
   target="_blank">Open results in a new window</a>
Discussions

javascript - jQuery open page in a new tab while passing POST data - Stack Overflow
I have a javascript variable called "list". I need to send it as a POST data to another page and open that page in a new tab (with the POST data present). This code: jQuery.post('datadestination.... More on stackoverflow.com
๐ŸŒ stackoverflow.com
javascript - Open new Tab or Window with POST [PHP] - Stack Overflow
2942 Open a URL in a new tab (and not a new window) 153 After submitting a POST form open a new window showing the result More on stackoverflow.com
๐ŸŒ stackoverflow.com
javascript - Opening a post request in a new tab - Stack Overflow
What I want to do in Angular is open a new tab and post data to it at the same time. This works great with creating a form element and submitting the form. The only issue is every input in a form M... More on stackoverflow.com
๐ŸŒ stackoverflow.com
May 24, 2017
javascript - How to replace window.open(...) with a POST - Stack Overflow
As far as I'm aware, this is going to force me to use a GET request. I would like to do this with a POST request. Is there a workaround for this? I'm not married to window.open(), either. I'm open to just about any alternative that allows me to spawn a new window via a POST request instead of a GET. More on stackoverflow.com
๐ŸŒ stackoverflow.com
Top answer
1 of 3
25

You can send a form using the target="_blank" attribute.

<form action="datadestination.php" method="POST" target="_blank" id="myform">
  <input type="hidden" name="list" id="list-data"/>
  <input type="submit" value="Submit">
</form>

Then in JS:

jQuery('#list-data').val(list);
jQuery('#myform').submit();
2 of 3
18

This is an implementation of Sergey's solution.

<?php // this is save.php
    session_start();
    // DO NOT just copy from _POST to _SESSION,
    // as it could allow a malicious user to override security.
    // Use a disposable variable key, such as "data" here.
    // So even if someone passed _POST[isAdmin]=true, all that he would do
    // is populate _SESSION[data][isAuthenticated], which nobody reads,
    // not the all-important _SESSION[isAuthenticated] key.
    if (array_key_exists('data', $_POST)) {
        $_SESSION['data']             = $_POST['data'];
        $_SESSION['data.timestamp']   = time();
        // Let us let the client know what happened
        $msg = 'OK';
    } else {
        $msg = 'No data was supplied';
    }
    Header('Content-Type: application/json; charset=utf8');
    die(json_encode(array('status' => $msg)));
?>

In the first page:

$.post('save.php', { data: list }, function(response){
    if (!response.status) {
        alert("Error calling save");
        return;
    }
    if (response.status !== 'OK') {
        alert(response.status);
        return;
    }
    // We had a response and it was "OK". We're good.
    window.open('datadestination.php');
});

And in datadestination.php add the fix:

if (!array_key_exists('data', $_SESSION)) {
   die("Problems? Did you perchance attempt to reload the page and resubmit?"); 
   // For if he did, then yes, $_SESSION would have been cleared.

   // Same if he is operating on more than one window or browser tab.
}
// Do something to validate data. For example we can use data.timestamp
// to assure data isn't stale.
$age = time();
if (array_key_exists($ts = 'data.timestamp', $_SESSION)) {
    _SESSION[$ts];
}
if ($age > 3600) {
    die("Data is more than one hour old. Did someone change server time?!?");
    // I actually had ${PFY} do that to me using NTP + --hctosys, once.
    // My own time zone is (most of the year) exactly one hour past GMT.
}

// This is safe (we move unsecurity-ward):
$_POST = $_SESSION['data'];
unset($_SESSION['data'], $_SESSION['data.timestamp']);
// keep things clean.

// From here on, the script behaves "as if" it got a _POST.

Update

You can actually merge save.php and datadestination.php and use a "saving stub" savepost.php that you can recycle in other pages:

<?php
    session_start();

    // DO NOT just copy from _POST to _SESSION,
    // as it could allow a malicious user to override security.
    // Use a disposable variable key, such as "data" here.
    if (array_key_exists('data', $_POST)) {
        // Timestamp sent by AJAX
        if (array_key_exists('ts', $_POST)) {
            // TODO: verify ts, but beware of time zones!
            $_SESSION['data'] = $_POST['data'];
            Header("Content-Type: application/json;charset=UTF-8");
            die(json_encode(array('status' => 'OK')));
        }
        die("Error");
    }
    // This is safe (we move unsecurity-ward):
    $_POST = $_SESSION['data'];
    unset($_SESSION['data']); // keep things clean.
?>

Now your call becomes

$.post('datadestination.php', { data: list, ts: Date.now() }, function(){
    window.open('datadestination.php');
});

and in your datadestination.php (or anywhere else) you add

require 'savepost.php';
๐ŸŒ
Taswar Bhatti
taswar.zeytinsoft.com โ€บ home โ€บ javascript http post data to new window or pop up
Javascript http post data to new window or pop up - Taswar Bhatti
August 22, 2014 - Here is how we do it, I created a blank html page first and used this javascript. ... By doing so we can pass in the data to the NewFile.aspx page with a post request now, also note if you are using Request.QueryString[โ€˜uidโ€™] in the NewFile.aspx page you will need to change it to Request[โ€˜uidโ€™] ... I did the exempleโ€ฆ But i notice that i donโ€™t need the window.open(..) line since on submit it open a new windowโ€ฆ
๐ŸŒ
Medium
medium.com โ€บ front-end-weekly โ€บ passing-data-to-new-window-using-javascript-3637c3a17f76
Passing data to new window using JavaScript | by Abhishek Ankush | Frontend Weekly | Medium
November 5, 2024 - Encoding Issues: Special characters must be properly encoded, which can complicate data retrieval and handling. 2. Post request: When launching the tab if we need to pass more data (for example to authenticate & authorize) and we canโ€™t do it via quary-params.
๐ŸŒ
codelessgenie
codelessgenie.com โ€บ blog โ€บ how-to-open-a-new-tab-with-a-post-request
How to Open a New Tab with a POST Request in JavaScript/jQuery: Sending Large JSON Data Without URL Parameters โ€” CodeLessGenie.com
Add form fields to hold your data (e.g., a single field for stringified JSON). Append the form to the DOM. Submit the form (triggering a new tab with the POST request). Clean up by removing the form from the DOM. Hereโ€™s a complete example using plain JavaScript. Weโ€™ll simulate a scenario where a user clicks a button to open a new tab with large JSON data.
Find elsewhere
๐ŸŒ
Codepad
codepad.co โ€บ snippet โ€บ javascript-open-new-window-posting-parameters
Javascript: Open new window POSTing parameters - Codepad
May 31, 2021 - openWindowWithPost("http://my.url.address/path", { param1: "value1", param2: "value2", //: }); function openWindowWithPost(url, data) { var form = document.createElement("form"); form.target = "_blank"; form.method = "POST"; form.action = url; form.style.display = "none"; for (var key in data) { var input = document.createElement("input"); input.type = "hidden"; input.name = key; input.value = data[key]; form.appendChild(input); } document.body.appendChild(form); form.submit(); document.body.removeChild(form); }
๐ŸŒ
Mozilla Bugzilla
bugzilla.mozilla.org โ€บ show_bug.cgi
1220758 - "Open in New Tab" on POST requests makes a GET request
So it really needs this resend-in-new-tab-functionality in console tab AND it has to include post vars. Get-only will surely help noone and if, he can simply copy the address and paste it. but why should you want to loose the POST data on purpose? I think this is a major problem, Firefox is not a useful webdevelopement machine without it any more... Sad. Here are some instructions for anyone interested in this bug. 1) Clean STR are in comment #0 2) The current implementation of "Open in New Tab." is here: https://dxr.mozilla.org/mozilla-central/rev/d0462b0948e0b1147dcce615bddcc46379bdadb2/devt
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 41098601 โ€บ opening-a-post-request-in-a-new-tab
javascript - Opening a post request in a new tab - Stack Overflow
May 24, 2017 - Using $http in Angular does this to the input data by default. On PHP side that means reading from "php://input" instead of $_POST. ... I think, it's not possible. Because, when you open new tab it's GET. ... I could change the backend as well, yes. But I don't want to put in a special case just for this if I don't have to. ... you could open a new tab and call "newTabPage.php" and in this file you send your request (with ajax) to get your data.
๐ŸŒ
IQCode
iqcode.com โ€บ code โ€บ javascript โ€บ jquery-window-new-tab-with-post
jquery window new tab with post Code Example
$.post(url, function (data) { var w = window.open('about:blank'); w.document.open(); w.document.write(data); w.document.clos...
Top answer
1 of 10
147

Instead of writing a form into the new window (which is tricky to get correct, with encoding of values in the HTML code), just open an empty window and post a form to it.

Example:

<form id="TheForm" method="post" action="test.asp" target="TheWindow">
<input type="hidden" name="something" value="something" />
<input type="hidden" name="more" value="something" />
<input type="hidden" name="other" value="something" />
</form>

<script type="text/javascript">
window.open('', 'TheWindow');
document.getElementById('TheForm').submit();
</script>

Edit:

To set the values in the form dynamically, you can do like this:

function openWindowWithPost(something, additional, misc) {
  var f = document.getElementById('TheForm');
  f.something.value = something;
  f.more.value = additional;
  f.other.value = misc;
  window.open('', 'TheWindow');
  f.submit();
}

To post the form you call the function with the values, like openWindowWithPost('a','b','c');.

Note: I varied the parameter names in relation to the form names to show that they don't have to be the same. Usually you would keep them similar to each other to make it simpler to track the values.

2 of 10
78

Since you wanted the whole form inside the javascript, instead of writing it in tags, you can do this:

let windowName = 'w_' + Date.now() + Math.floor(Math.random() * 100000).toString();
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "openData.do");

form.setAttribute("target", windowName);

var hiddenField = document.createElement("input"); 
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", "message");
hiddenField.setAttribute("value", "val");
form.appendChild(hiddenField);
document.body.appendChild(form);

window.open('', windowName);

form.submit();
๐ŸŒ
Oodlestechnologies
oodlestechnologies.com โ€บ blogs โ€บ open-popup-window-with-http-post-data-javascript
Open popup window with http POST data Javascript
February 14, 2020 - function openPopupPage(relativeUrl, emailId, age) { var param = { 'emailId' : emailId, 'age': age }; OpenWindowWithPost(relativeUrl, "width=1000, height=600, left=100, top=100, resizable=yes, scrollbars=yes", "NewFile", param); } function OpenWindowWithPost(url, windowoption, name, params) { var form = document.createElement("form"); form.setAttribute("method", "post"); form.setAttribute("action", url); form.setAttribute("target", name); for (var i in params) { if (params.hasOwnProperty(i)) { var input = document.createElement('input'); input.type = 'hidden'; input.name = i; input.value = params[i]; form.appendChild(input); } } document.body.appendChild(form); //note I am using a post.htm page since I did not want to make double request to the page //it might have some Page_Load call which might screw things up.
Top answer
1 of 2
2

The magic trick is using target attribute of form element. You can submit using javascript with below code

<script type="text/javascript">
function openWindowWithPost(url, data) {
    var dataForm = document.createElement("form");
    dataForm.style.display = "none";
    dataForm.target = "TargetWindow";//Make sure the window name is same as this value
    dataForm.method = "POST";
    dataForm.action = url;
    for (var key in data) {
        var postData = document.createElement("input");
        postData.type = "hidden";
        postData.name = key;
        postData.value = data[key];
        dataForm.appendChild(postData);
    }
    document.body.appendChild(dataForm);
    var postWindow = window.open("", "TargetWindow", "status=0,title=0,height=600,width=800,scrollbars=1");
    if (postWindow) {
        dataForm.submit();
    } else {
        alert('You must allow popups for this map to work.');
    }
    //For testing invoking this function
    openWindowWithPost("http://google.com", {q: 'search', from: 'custom'})
}
</script>

Same behavior can be achieved with

<!DOCTYPE html>
<html lang="en">
    <head><meta charset="utf-8" /><title>Test</title></head>
<body>
  <form method="POST" enctype="multipart/form-data" target="TargetWindow" action="http://google.com" onsubmit="openTargetWindowAndSubmit()">
    <input type="file" accept="image/*" />
    <input type="submit" value="Submit"/>
  </form>
  <script type="text/javascript">
  function openTargetWindowAndSubmit() {
    //We are just making sure the target window is available before submiting the form
    window.open("", "TargetWindow", "status=0,title=0,height=600,width=800,scrollbars=1");
  }
  </script>
</body>
</html>

Note: Using simply target='_blank' or target='TargetWindow' opens generally a new tab. This is fine when new tab is OK with you. But when you want to submit in POP UP window, than giving the window width and height is required.

2 of 2
0

So your only option would be to create a form, set the target to _blank, and trigger the submission.

<form action="/action" method="post" target="_blank" id="frm">
   <input type="hidden" name="foo" value="your huge string">
</form>

You can create it with JavaScript and submit it.

document.getElementById("frm").submit()
๐ŸŒ
Google Groups
groups.google.com โ€บ g โ€บ google-web-toolkit โ€บ c โ€บ 9BQFfiO6fzg
How to send Post-Data to Window.open?
> If not, what other possibilities do I have? You can send a POST in response to which the server generates a temporary file and sends back the URL to that file, and then use Window.open with that URL to open the generated file in a new window.
๐ŸŒ
Attacomsian
attacomsian.com โ€บ blog โ€บ javascript-open-url-in-new-tab
Open a URL in a new tab or window on button click in JavaScript
October 12, 2022 - In JavaScript, you can use the window.open() method to open a URL in a new tab on a button click.