120

I am trying to read the post request parameters from my HTML. I can read the get request parameters using the following code in JavaScript.

$wnd.location.search

But it does not work for post request. Can anyone tell me how to read the post request parameter values in my HTML using JavaScript?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
DonX
  • 16,093
  • 21
  • 75
  • 120

18 Answers18

227

POST data is data that is handled server side. And Javascript is on client side. So there is no way you can read a post data using JavaScript.

rahul
  • 184,426
  • 49
  • 232
  • 263
  • 84
    Although the conclusion is correct (you can't get that data from javascript) the reasoning is wrong. The client (the browser) is the one that sends the POST data to the server in the first place. So the client knows very well what that data is. The actual reason is simply that the browser doesn't make that data available to javascript (but it perfectly could). – GetFree Jun 12 '13 at 23:23
  • @GetFree: What good is this so-called knowledge of the POST variables to a web developer? No web developer will write a client-side script predicated on the browser possibly making the post data available to JavaScript since, as you point out, it *never happens in practice*. Thus, in the *real world*, the answer presented here is correct, as well as my own. – Platinum Azure Jun 13 '13 at 04:16
  • 41
    @PlatinumAzure, I'm not sure you understand the point. You say the POST data exists in the server, and since javascript runs in the client, there is no way that JS could access that data. That is wrong, the POST data exist both in the client and the server and the reason why JS can't access that data is simply because the client (the browser) doesn't make it available to JS. As simple as that. – GetFree Jun 13 '13 at 18:41
  • @GetFree: You're splitting hairs. This is a programming website. On this programming website, a question arises about how to access POST data in JavaScript. It can't be done (for whatever reason you care to rant about) unless a server-side script spits out the values into the JavaScript code. That's all that matters here. – Platinum Azure Jun 13 '13 at 22:19
  • 14
    @PlatinumAzure, Yes, it can't be done for whatever reason. But if you are going to explain what that reason is, make sure it's the right reason. You explanation of why it's not possible is wrong, that's the point. – GetFree Jun 13 '13 at 23:31
  • 12
    Since browsers are getting things like web apps, apps running (often) 100 percent in the browser (no server, other than hosting files), it will become a natural need to be able to receive larger chunks of data. There is a limit on the size of query string (GET method) (think 4K), so the ability to read larger chunks of POSTED data from javascript would be a great idea IMHO. – Netsi1964 Feb 07 '14 at 08:12
  • @GetFree hey my question is completely off the topic but I wanted to know that whether its possible to see whether the post or get data being sent by a webpage to its server can be read or not. eg if i have a site say xyz.com and I have a form in that. So is it possible that say, an add on will be able to read what data is being sent by xyz. – sss999 Sep 03 '16 at 04:56
  • @sss999, if you are talking about a regular webpage add-on, then NO. That data is not made available to Javascript. But if you are talking about installed add-ons/plug-ins, that's another story. Most browsers do give that data to add-ons/plug-ins/extensions. Implementation details differ from browser to browser, though. – GetFree Sep 04 '16 at 19:52
  • @GetFree I am talking about an installed plugin on Chrome. Any link or any video that would help to tell how is it done? – sss999 Sep 04 '16 at 20:50
  • Came here point out that this has nothing to do with client/server as the answer states as its reason. If GET data is available POST could be available as well, like @GetFree states it is simply what the browsers decided not to make it available probably because unlike GET the POST data doe snot have restrictions. Some day it is possible that we will get the feature with some constraints on the size. – bhantol Oct 05 '20 at 15:56
30

A little piece of PHP to get the server to populate a JavaScript variable is quick and easy:

var my_javascript_variable = <?php echo json_encode($_POST['my_post'] ?? null) ?>;

Then just access the JavaScript variable in the normal way.

Note there is no guarantee any given data or kind of data will be posted unless you check - all input fields are suggestions, not guarantees.

Iiridayn
  • 1,747
  • 21
  • 43
Roger
  • 357
  • 3
  • 2
  • 14
    Be careful to escape/add quotes/etc. to your POST data if you go this route. An alternative is to use json_encode(), which will work for pretty much any data type. Example: http://www.abeautifulsite.net/passing-data-from-php-to-javascript/ – claviska Jun 14 '15 at 00:59
  • 1
    Now this is what I call thinking out of the box. – see Jan 15 '17 at 12:18
  • This is the simplest way to do this for sure. This worked for me in wordpress by creating a new theme page and simply exposing the post data at the window level like window.my_prefix_post_data = ; and then accessing the post data from any scope easily that way. This wouldn't be recommended for sites with a lot of sensitive post data going thru all the time, but for the scope of our page / site it works great. – OG Sean Feb 08 '18 at 23:58
  • 3
    this is not viable, there could be character escape issue. – MathieuAuclair Apr 09 '18 at 05:18
  • 2
    Hacked, for sure. Don't use the above method without escaping. – reggie Jul 31 '19 at 10:22
15

JavaScript is a client-side scripting language, which means all of the code is executed on the web user's machine. The POST variables, on the other hand, go to the server and reside there. Browsers do not provide those variables to the JavaScript environment, nor should any developer expect them to magically be there.

Since the browser disallows JavaScript from accessing POST data, it's pretty much impossible to read the POST variables without an outside actor like PHP echoing the POST values into a script variable or an extension/addon that captures the POST values in transit. The GET variables are available via a workaround because they're in the URL which can be parsed by the client machine.

mkb0517
  • 3
  • 3
Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
  • 3
    I emphatically disagree with your -1. Nowhere in the OP did the question specify AJAX, so that leaves open the possibility of link clicks and form submits not performed by JavaScript. The latter in particular is an example where POST variables exists but are not available on the client side, unless the server response is generated by a script and the script elects to echo the values of the POST variables into the JS code. If I could -1 your comment, I would. – Platinum Azure Jun 13 '13 at 04:10
  • 2
    I'm not talking about AJAX. My argument refers to any form of POST request. The browser knows every parameter sent as part of the HTTP request, that includes, among others, the URL and the POST parameters. Some of those parameters are made available to javascript others are not. It's simply a restriction imposed by the browser, it could very well give access to the POST params from JS, but it doesn't, that's the simple truth. – GetFree Jun 13 '13 at 18:51
  • 1
    You're not getting my point. Nobody will write a JavaScript expecting the POST variables to be available unless the server explicitly provides them. If the server does not provide them, then as far as a web developer writing JavaScript code is concerned, they might as well not be on the client side at all. – Platinum Azure Jun 13 '13 at 22:18
  • 3
    My explanation was incomplete, not wrong. I've edited my answer so that even you should be happy. If you're not, then instead of giving me -1 and snide comments, edit it yourself. – Platinum Azure Jun 14 '13 at 05:14
  • I really don't think GET variables are a fluke, could you site some references for that please? – OG Sean Feb 08 '18 at 23:58
  • 1
    What I meant by that is, a server isn't exposing them to the client as GET data, but rather the client is able to re-parse the URL for them. POST data, on the other hand, will not be in the URL. Happy to change the language if you like, but the claim is not under dispute. – Platinum Azure Feb 10 '18 at 01:20
14

Use sessionStorage!

$(function(){
    $('form').submit{
       document.sessionStorage["form-data"] =  $('this').serialize();
       document.location.href = 'another-page.html';
    }
});

At another-page.html:

var formData = document.sessionStorage["form-data"];

Reference link - https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

  • What if the post request comes from a subdomain or another domain? Conception busted. – undefined May 30 '19 at 08:48
  • It should be `form.on('submit',function(){document.sessionStorage["form-data"] = $('this').serialize();window.location.href = 'another-page.html';})` – Justin Liu May 28 '20 at 16:36
  • @ZefirZdravkov You could set a cookie with `samesite = None` and `Secure` so chrome allows it's use. – Justin Liu May 28 '20 at 16:37
  • thanks @Alexandre Parpinelli that's what I am looking for, this method is also useful if you don't have control over serverside. – Nitin Shinde Aug 19 '22 at 12:45
  • @JustinLiu, can you provide a complete example? I am new here. I'd like to see a complete 1st html page and a complete 2nd html page. Thank you – oldpride Jun 19 '23 at 19:50
6

Why not use localStorage or any other way to set the value that you would like to pass?

That way you have access to it from anywhere!

By anywhere I mean within the given domain/context

Ian Mbae
  • 138
  • 1
  • 2
  • 13
  • 3
    why not just a simple cookie? – Redoman Jan 10 '18 at 10:17
  • 1
    What if the post request comes from a subdomain or another domain? Conception busted. – undefined May 30 '19 at 08:46
  • @ZefirZdravkov, while I agree with you on the existence of the given limitation, it exists due to browser-based security implementations. I can only imagine the limitless horror if it was an 'any site can read any other`s content' scenario. – Ian Mbae Jun 03 '19 at 08:17
  • @Ian Any site can actually read any other's content via CURL or Ajax. If referring to 'any other site's localStorage', then, yes, that would be abominable. All I am saying is this answer would only work if you are receiving/sending POST requests to this domain only. For instance, a POST request from `cloudianos.com` would not reach `api.cloudianos.com`'s JavaScript, for they don't share the same `localStorage`. – undefined Jun 03 '19 at 13:30
3

If you're working with a Java / REST API, a workaround is easy. In the JSP page you can do the following:

    <%
    String action = request.getParameter("action");
    String postData = request.getParameter("dataInput");
    %>
    <script>
        var doAction = "<% out.print(action); %>";
        var postData = "<% out.print(postData); %>";
        window.alert(doAction + " " + postData);
    </script>
Felix G.
  • 6,365
  • 2
  • 16
  • 24
user3260912
  • 603
  • 2
  • 7
  • 19
2

You can read the post request parameter with jQuery-PostCapture(@ssut/jQuery-PostCapture).

PostCapture plugin is consisted of some tricks.

When you are click the submit button, the onsubmit event will be dispatched.

At the time, PostCapture will be serialize form data and save to html5 localStorage(if available) or cookie storage.

ssut
  • 431
  • 2
  • 8
2

I have a simple code to make it:

In your index.php :

<input id="first_post_data" type="hidden" value="<?= $_POST['first_param']; ?>"/>

In your main.js :

let my_first_post_param = $("#first_post_data").val();

So when you will include main.js in index.php (<script type="text/javascript" src="./main.js"></script>) you could get the value of your hidden input which contains your post data.

1

POST is what browser sends from client(your broswer) to the web server. Post data is send to server via http headers, and it is available only at the server end or in between the path (example: a proxy server) from client (your browser) to web-server. So it cannot be handled from client side scripts like JavaScript. You need to handle it via server side scripts like CGI, PHP, Java etc. If you still need to write in JavaScript you need to have a web-server which understands and executes JavaScript in your server like Node.js

kiranvj
  • 32,342
  • 7
  • 71
  • 76
1

It depends of what you define as JavaScript. Nowdays we actually have JS at server side programs such as NodeJS. It is exacly the same JavaScript that you code in your browser, exept as a server language. So you can do something like this: (Code by Casey Chu: https://stackoverflow.com/a/4310087/5698805)

var qs = require('querystring');

function (request, response) {
    if (request.method == 'POST') {
        var body = '';

        request.on('data', function (data) {
            body += data;

            // Too much POST data, kill the connection!
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6)
                request.connection.destroy();
        });

        request.on('end', function () {
            var post = qs.parse(body);
            // use post['blah'], etc.
        });
    }
}

And therefrom use post['key'] = newVal; etc...

William R.
  • 145
  • 1
  • 11
1
<script>
<?php
if($_POST) { // Check to make sure params have been sent via POST
  foreach($_POST as $field => $value) { // Go through each POST param and output as JavaScript variable
    $val = json_encode($value); // Escape value
    $vars .= "var $field = $val;\n";
  }
  echo "<script>\n$vars</script>\n";
}
?>
</script>

Or use it to put them in an dictionary that a function could retrieve:

<script>
<?php
if($_POST) {
  $vars = array();
  foreach($_POST as $field => $value) {
    array_push($vars,"$field:".json_encode($value)); // Push to $vars array so we can just implode() it, escape value
  }
  echo "<script>var post = {".implode(", ",$vars)."}</script>\n"; // Implode array, javascript will interpret as dictionary
}
?>
</script>

Then in JavaScript:

var myText = post['text'];

// Or use a function instead if you want to do stuff to it first
function Post(variable) {
  // do stuff to variable before returning...
  var thisVar = post[variable];
  return thisVar;
}

This is just an example and shouldn't be used for any sensitive data like a password, etc. The POST method exists for a reason; to send data securely to the backend, so that would defeat the purpose.

But if you just need a bunch of non-sensitive form data to go to your next page without /page?blah=value&bleh=value&blahbleh=value in your url, this would make for a cleaner url and your JavaScript can immediately interact with your POST data.

electrikmilk
  • 1,013
  • 1
  • 11
  • 23
0

You can 'json_encode' to first encode your post variables via PHP. Then create a JS object (array) from the JSON encoded post variables. Then use a JavaScript loop to manipulate those variables... Like - in this example below - to populate an HTML form form:

<script>

    <?php $post_vars_json_encode =  json_encode($this->input->post()); ?>

    // SET POST VALUES OBJECT/ARRAY
    var post_value_Arr = <?php echo $post_vars_json_encode; ?>;// creates a JS object with your post variables
    console.log(post_value_Arr);

    // POPULATE FIELDS BASED ON POST VALUES
    for(var key in post_value_Arr){// Loop post variables array

        if(document.getElementById(key)){// Field Exists
            console.log("found post_value_Arr key form field = "+key);
            document.getElementById(key).value = post_value_Arr[key];
        }
    }


</script>
TV-C-1-5
  • 680
  • 2
  • 13
  • 19
0
function getParameterByName(name, url) {
            if (!url) url = window.location.href;
            name = name.replace(/[\[\]]/g, "\\$&");
            var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
                results = regex.exec(url);
            if (!results) return null;
            if (!results[2]) return '';
            return decodeURIComponent(results[2].replace(/\+/g, " "));
        }
var formObj = document.getElementById("pageID");
formObj.response_order_id.value = getParameterByName("name");
le cuong
  • 11
  • 1
  • This is GET variable, OP asked specifically for POST var and noted he already has GET variables easily. – OG Sean Feb 09 '18 at 00:00
0

One option is to set a cookie in PHP.

For example: a cookie named invalid with the value of $invalid expiring in 1 day:

setcookie('invalid', $invalid, time() + 60 * 60 * 24);

Then read it back out in JS (using the JS Cookie plugin):

var invalid = Cookies.get('invalid');

if(invalid !== undefined) {
    Cookies.remove('invalid');
}

You can now access the value from the invalid variable in JavaScript.

Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
-1

POST variables are only available to the browser if that same browser sent them in the first place. If another website form submits via POST to another URL, the browser will not see the POST data come in.

SITE A: has a form submit to an external URL (site B) using POST SITE B: will receive the visitor but with only GET variables

Chris Denman
  • 1,187
  • 3
  • 9
  • 15
-3
$(function(){
    $('form').sumbit{
        $('this').serialize();
    }
});

In jQuery, the above code would give you the URL string with POST parameters in the URL. It's not impossible to extract the POST parameters.

To use jQuery, you need to include the jQuery library. Use the following for that:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"></script>
John Washam
  • 4,073
  • 4
  • 32
  • 43
Bunny Rabbit
  • 8,213
  • 16
  • 66
  • 106
  • 4
    This would only get the POST parameters on the page where the form is being submitted **from**. It seems a safe assumption the OP wants to get POST parameters on the page the form was submitted **to**. That is impossible to do. – John Washam Oct 29 '14 at 21:18
-3

We can collect the form params submitted using POST with using serialize concept.

Try this:

$('form').serialize(); 

Just enclose it alert, it displays all the parameters including hidden.

rasso
  • 2,131
  • 3
  • 21
  • 24
praveen
  • 61
  • 1
  • 4
-4
<head><script>var xxx = ${params.xxx}</script></head>

Using EL expression ${param.xxx} in <head> to get params from a post method, and make sure the js file is included after <head> so that you can handle a param like 'xxx' directly in your js file.