Enquiry Email Form

I’m quickly going to show you how to pass a variable into window.location – I’ve recently read a few discussion forums where people have been struggling with this. It’s really simple to accomplish, and that’s why it’s so frustrating when getting stuck on a problem like this.

The Scenario

1
2
3
4
5
6
 
//your variable
var data = "brightcherry";
 
//you want to pass the variable into the window.location URL
window.location.replace("/admin/products/view.php?data=brightcherry);

As said, the solution is simple, and from what I’ve seen, people seemed to be getting confused with the syntax of the quoting. There are a few solutions to this getting this to work.

Solution 1

1
2
3
4
5
6
 
//your variable
var data = "brightcherry";
 
//passing the variable into the window.location URL
window.location.replace("/newpage/page.php?id='"+product_id+"'");

Solution 2

1
2
3
4
5
6
 
//your variable
var data = "brightcherry";
 
//passing the variable into the window.location URL
window.location.replace("/newpage/page.php?id=" + product_id);

I hope this blog post has managed to ease someone’s frustration 🙂

  1. Dimas
    16/05/2012

    nice..
    But what if there are two variables.

    //your variable
    var data = “brightcherry”;
    var data2= “test”;

  2. DoubleAgent
    18/05/2012

    for two variables, do it the same way as his second code;)

    //example from my project:
    // polozka and eshop are variables

    window.location = “sprava.php?smazat=”+polozka+”&sprava=”+eshop+””;

  3. Jackson
    03/09/2012

    The post was helpful, but I already knew about the GET method of variable passage. Is there a way, for security purposes, to pass the information via POST? I currently use cookies and would rather do something more secure since cookies can be created by a user…

  4. 05/08/2013

    @Jackson Technically, so can POST data, though it does take a tiny bit more doing; it’s trivial with a browser plugin such as Firebug. Don’t ever think POST data is by itself secure.

Learning & sharing

This is where we store some of our Web Development thoughts, tips and tricks for both our own uses and for others to learn from. Sharing is caring.

Please feel free to contribute to our blog posts; perhaps even teach us a few tricks of your own. We'd love to hear your thoughts.



X