124

When using window.location.href, I'd like to pass POST data to the new page I'm opening. is this possible using JavaScript and jQuery?

Brian
  • 24,052
  • 51
  • 126
  • 164

9 Answers9

87

Using window.location.href it's not possible to send a POST request.

What you have to do is to set up a form tag with data fields in it, set the action attribute of the form to the URL and the method attribute to POST, then call the submit method on the form tag.

Guffa
  • 640,220
  • 96
  • 678
  • 956
  • I have data coming from 3 different forms and I am trying to send all 3 forms to the same page so I've been trying to serialize the forms with jQuery and send them some other way – Brian Mar 03 '10 at 01:55
  • @Brian: Can't you just put everything in one `form`, so everything is sent together automatically? – Marcel Korpel Mar 03 '10 at 02:26
  • One form is in a jQueryUI dialog box - so I can't just include them all. – Brian Mar 03 '10 at 02:42
  • 12
    Pull out all their values, _dynamically_ build a form with all of the fields in all three forms, and submit that form. The form can be invisible. Don't use a JQuery AJAX method, use `$("#myForm").submit()`. The form- which will be invisible, and only used to submit values from your client side code, not user input- will never be shown nor otherwise used, and the page will be refreshed. – Matt Luongo Mar 03 '10 at 05:36
84

Add a form to your HTML, something like this:

<form style="display: none" action="/the/url" method="POST" id="form">
  <input type="hidden" id="var1" name="var1" value=""/>
  <input type="hidden" id="var2" name="var2" value=""/>
</form>

and use JQuery to fill these values (of course you can also use javascript to do something similar)

$("#var1").val(value1);
$("#var2").val(value2);

Then finally submit the form

$("#form").submit();

on the server side you should be able to get the data you sent by checking var1 and var2, how to do this depends on what server-side language you are using.

Denis P
  • 13
  • 4
Mohamed Khamis
  • 6,495
  • 9
  • 35
  • 57
14

As it was said in other answers there is no way to make a POST request using window.location.href, to do it you can create a form and submit it immediately.

You can use this function:

function postForm(path, params, method) {
    method = method || 'post';

    var form = document.createElement('form');
    form.setAttribute('method', method);
    form.setAttribute('action', path);

    for (var key in params) {
        if (params.hasOwnProperty(key)) {
            var hiddenField = document.createElement('input');
            hiddenField.setAttribute('type', 'hidden');
            hiddenField.setAttribute('name', key);
            hiddenField.setAttribute('value', params[key]);

            form.appendChild(hiddenField);
        }
    }

    document.body.appendChild(form);
    form.submit();
}

postForm('mysite.com/form', {arg1: 'value1', arg2: 'value2'});

https://stackoverflow.com/a/133997/2965158

Aquajet
  • 544
  • 5
  • 12
9

Use this file : "jquery.redirect.js"

$("#btn_id").click(function(){
    $.redirect(http://localhost/test/test1.php,
        {
            user_name: "khan",
            city : "Meerut",
            country : "country"
        });
    });
});

see https://github.com/mgalante/jquery.redirect

Tirzono
  • 416
  • 2
  • 10
8

Short answer: no. window.location.href is not capable of passing POST data.

Somewhat more satisfying answer: You can use this function to clone all your form data and submit it.

var submitMe = document.createElement("form");
submitMe.action = "YOUR_URL_HERE"; // Remember to change me
submitMe.method = "post";
submitMe.enctype = "multipart/form-data";
var nameJoiner = "_";
// ^ The string used to join form name and input name
//   so that you can differentiate between forms when
//   processing the data server-side.
submitMe.importFields = function(form){
    for(k in form.elements){
        if(input = form.elements[k]){
            if(input.type!="submit"&&
                     (input.nodeName=="INPUT"
                    ||input.nodeName=="TEXTAREA"
                    ||input.nodeName=="BUTTON"
                    ||input.nodeName=="SELECT")
                     ){
                var output = input.cloneNode(true);
                output.name = form.name + nameJoiner + input.name;
                this.appendChild(output);
            }
        }
    }
}
  • Do submitMe.importFields(form_element); for each of the three forms you want to submit.
  • This function will add each form's name to the names of its child inputs (If you have an <input name="email"> in <form name="login">, the submitted name will be login_name.
  • You can change the nameJoiner variable to something other than _ so it doesn't conflict with your input naming scheme.
  • Once you've imported all the necessary forms, do submitMe.submit();
joequincy
  • 1,375
  • 10
  • 20
4

it's as simple as this

$.post({url: "som_page.php", 
    data: { data1: value1, data2: value2 }
    ).done(function( data ) { 
        $( "body" ).html(data);
    });
});

I had to solve this to make a screen lock of my application where I had to pass sensitive data as user and the url where he was working. Then create a function that executes this code

Sergio Roldan
  • 59
  • 1
  • 5
4

Have you considered simply using Local/Session Storage? -or- Depending on the complexity of what you're building; you could even use indexDB.

note:

Local storage and indexDB are not secure - so you want to avoid storing any sensitive / personal data (i.e names, addresses, emails addresses, DOB etc) in either of these.

Session Storage is a more secure option for anything sensitive, it's only accessible to the origin that set the items and also clears as soon as the browser / tab is closed.

IndexDB is a little more [but not much more] complicated and is a 30MB noSQL database built into every browser (but can be basically unlimited if the user opts in) -> next time you're using Google docs, open you DevTools -> application -> IndexDB and take a peak. [spoiler alert: it's encrypted].

Focusing on Local and Session Storage; these are both dead simple to use:

// To Set 
sessionStorage.setItem( 'key' , 'value' );

// e.g.
sessionStorage.setItem( 'formData' , { name: "Mr Manager", company: "Bluth's Frozen Bananas", ...  } );    

// Get The Data 
const fromData = sessionStorage.getItem( 'key' );     

// e.g. (after navigating to next location)
const fromData = sessionStorage.getItem( 'formData' );

// Remove 
sessionStorage.removeItem( 'key' );

// Remove _all_ saved data sessionStorage
sessionStorage.clear( ); 

If simple is not your thing -or- maybe you want to go off road and try a different approach all together -> you can probably use a shared web worker... y'know, just for kicks.

Qrazier
  • 143
  • 3
  • 13
1

I use a very different approach to this. I set browser cookies in the client that expire a second after I set window.location.href.

This is way more secure than embedding your parameters in the URL.

The server receives the parameters as cookies, and the browser deletes the cookies right after they are sent.

const expires = new Date(Date.now() + 1000).toUTCString()
document.cookie = `oauth-username=user123; expires=${expires}`
window.location.href = `https:foo.com/oauth/google/link`
Steven Spungin
  • 17,551
  • 4
  • 57
  • 56
-4

You can use GET instead of pass, but don't use this method for important values,

function passIDto(IDval){    
window.location.href = "CustomerBasket.php?oridd=" +  IDval ;
}   

In the CustomerBasket.php

<?php
  $value = $_GET["oridd"];
  echo  $value;
?>
Kissa Mia
  • 287
  • 7
  • 22
  • 3
    its GET method but question is POST method buddy – Thamaraiselvam Sep 21 '15 at 07:06
  • @thamaraiselvam Kissa Mia may not have phrased the answer well but is right about the GET route here. The question is not hardwired to using the POST method - the user just asked if there was a way to take *POST data* and send it via window.location.href. And you should first know that Window.location.href **IS** a GET request. This answer is not wrong - it simply won't be easy to scale to a large number of form fields, encoded as a QueryString. However, the most obvious way of sending data via a URL (which is what you can change with window.location.href) is via query string parameters. – SylonZero Feb 04 '17 at 03:01
  • @SylonZero You can't attach POST data to a GET request. They are different kinds of requests and the data looks different in a POST. The important parts of the HTTP spec are fairly short. – Colin vH Jul 11 '17 at 16:20
  • @ColinvH You need to read what I've written more carefully. TLDR version: you can take the data that would be used to generate a POST and encode it as query string params. – SylonZero Jul 11 '17 at 18:01