24
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>    
<script type="text/javascript">
    function DoPost(){
      $.post("index.html", { name: "John", time: "2pm" } );
   }
    </script>
</head>

<body>
<a href="javascript:DoPost()">GO</a>

</body>
</html>

I made function and trying to call that function, inside that function I mentioned url and data as mentioned here. But, It's not working for me.

NOTE : Even I mentioned in my post title, then also I want to clarify that, I want to navigate to another page using POST method through simple hyperlink.

Ravi
  • 30,829
  • 42
  • 119
  • 173
  • You know that `$.post` makes an `AJAX` request? If you want to navigate using a `POST` request you can use a form. – a better oliver Jun 29 '13 at 09:26
  • Ok... but I want this in simple link, so is there any way to perform this. ? – Ravi Jun 29 '13 at 09:27
  • Well, a form is simpler than this solution imho. Using `$.post` you could take the response and write it to the document, but that's not exactly the same as loading a new page. So, no, it's not possible with a link or JavaScript. – a better oliver Jun 29 '13 at 09:36

7 Answers7

21

Create an html form with all the data you need to send and specify as action the page you need to forward the user.

<form method="post" id="theForm" action="REDIRECT_PAGE.php">

Then put some hidden fields in that form.

<input type="hidden" name="name" value="John">
<input type="hidden" name="time" value="2pm">
</form>

Wrap this inside of your doRedirect function and the redirect will work while correctly submitting your POST data.

document.getElementById('theForm').submit()

As a side note, you may want to redirect the user to a .php page not a .html one if you need to read POST data. This depends on your server configuration but, by default, I don't think you can run PHP code inside of a .html file.

Saturnix
  • 10,130
  • 17
  • 64
  • 120
  • hahaha.... don't worry, I'll.. and I didn't mean that, I was just saying that, you were little late, because, I already made it. Not because I post it earlier than you.. ;) – Ravi Jun 29 '13 at 10:18
  • Remember doRedirect will only work if DOM is ready... Not a big deal thou, since you display it in a link. I would recommend placing the form before the link which displays the doRedirect function. Bye! – Saturnix Jun 29 '13 at 10:20
  • fantastic, haven't thought of that! – Toma Dec 23 '20 at 13:49
18

I know this question is almost 4 years old and there is already an accepted answer, but I would like to provide an alternative solution as well as point out your mistake.

Part 1: The Solution

The conventional solution for navigating with a POST request is a form, which the accepted answer uses. I will build on top of this by presenting a solution to programmatically create forms using DOM.

var payload = {
  name: 'John',
  time: '2pm'
};
var form = document.createElement('form');
form.style.visibility = 'hidden'; // no user interaction is necessary
form.method = 'POST'; // forms by default use GET query strings
form.action = 'index.html';
for (key in Object.keys(payload)) {
  var input = document.createElement('input');
  input.name = key;
  input.value = payload[key];
  form.appendChild(input); // add key/value pair to form
}
document.body.appendChild(form); // forms cannot be submitted outside of body
form.submit(); // send the payload and navigate

I used index.html as per your original code, but I would take the accepted answer's advice and use PHP to accept and process the POST data.

Part 2: The Problem

The main problem with your original solution is that it used $.post, a helper function built on top of $.ajax. AJAX is meant to be used when retrieving data from a server and using it within current page, rather than navigating to another page.

Community
  • 1
  • 1
robbie
  • 1,219
  • 1
  • 11
  • 25
  • 1
    I was going to suggest appending this line: `document.removeChild(form);` however, the whole point is navigating away from the page so it really doesn't matter :-P . Great solution, i'll be using this on my project. – Kemuel Sanchez Oct 12 '17 at 14:59
8

This should work fine. Similar to one answer, but a better one.

var payload = {
  name: 'John',
  time: '2pm'
};
var form = document.createElement('form');
form.style.visibility = 'hidden';
form.method = 'POST';
form.action = link;
$.each(Object.keys(payload), function(index, key) {
var input = document.createElement('input');
    input.name = key;
    input.value = payload[key];
    form.appendChild(input)
});
document.body.appendChild(form);
form.submit();
IamMHussain
  • 716
  • 8
  • 11
  • How is this better? Replacing `for .. in` with `$.each` is slower, and if you are using jQuery, you should have rewritten the whole answer in jQuery. This is not better by any means. – hndcrftd Oct 28 '20 at 21:25
0

Finally, I did it, but not exactly as I wanted. But it is helpful for me. Now, sharing for others

<html>
  <head>
    <script type="text/javascript">
      function DoPost() {
        document.postlink.submit();
      }   
    </script>
  </head>

  <body>
    <a href="javascript:DoPost()">GO</a>
    <form action="demo.php" name="postlink" method="post">
      <input type="hidden" name="name" value="this is my POST data">
    </form>
  </body>
</html>
Vlad
  • 1,017
  • 1
  • 15
  • 18
Ravi
  • 30,829
  • 42
  • 119
  • 173
0
function js_navigate_with_post(js_url, js_post_params)
{
    var js_html='';
    js_html += "<form id='js_navigate_with_post' method='post' action='"+js_url+"'>\n";
    js_html +=  "<input type='hidden' name='js_navigate_with_post' value='true'>\n";
    for (var js_key in js_post_params) {
        if (js_post_params.hasOwnProperty(js_key))
        {
            js_html +=  "<input type='hidden' name='"+js_key+"' value='"+js_post_params[js_key]+"'>\n";
        }
    }
    js_html += "</form>\n";
    jQuery('body').append(js_html);
    jQuery('#js_navigate_with_post').submit();
}
ihorsl
  • 15
  • 1
0

I got it working finally in one of my projects.

You can try

<html>
<head>
</head>

<body>
<button id="clickme">GO</button>

</body>
<script>
$("#clickme").click(function(e){
    var myForm = '<form id="ff" action="page2.php" method="POST">\
        <input name="name" value="John">\
        <input name="time" value="2pm">\
    </form>';
    $('body').append(myForm);
    $('#ff').submit();
    $('#ff').remove();
});
</script>
</html>
<html>
parv desai
  • 387
  • 2
  • 6
  • 15
-1

What do you mean it is not working? How can it work when you post results to a simple .html page?

The $.post function is a shorthand for $.ajax, which I always found easier to read and debug! Please have a look again in the link that you provided and see the examples in the bottom of the page!

For example:

$.post("test.php", { name: "John", time: "2pm" } );

Update: No, it shouldn't go to the index.html. What your code actually does is sending post variables to an .html page, so basically it doesn't do that much. That said, you can do what you want with many different solutions, see two of them below:

  • You can either add an done event on the $.post function, for example:

    $.post("test.php", { name: "John", time: "2pm" } ).done(function() { alert("Success, do the redirection here!"); });

  • Or maybe maybe redirect using get variables instead of post ones? for example:

    window.location = "index.php?username=blah&pass=blah"; and deal with them in the php page.

ps. the above solution obviously is for testing purposes, if you go that way you will have somehow to encrypt your data!

Dennis Tsoumas
  • 132
  • 1
  • 13
  • not working means.. when I click `GO`, it should move to `index.html` page as mentioned in `url` value. But, nothing happens, according to me it is not working. – Ravi Jun 29 '13 at 09:26
  • so use @Vahe Yepremyan's solution – mkutyba Jun 29 '13 at 09:28
  • @matty I request you, please read my post. Because, I need post request, if it is not possible, then please let me know. Because Vahe solution is simple javascript to move to another page. – Ravi Jun 29 '13 at 09:30
  • @jWeavers You wrote it should move to index.html page. So that was solution. If you expect something else please describe it in your question because you are not accurate. – mkutyba Jun 29 '13 at 09:42
  • may be I'm wrong,while explaining my problem, but if you see, I mentioned my post title `with post request`. May be you missed that. – Ravi Jun 29 '13 at 09:44