a.litis
a.litis

Reputation: 443

How to pass 2 JavaScript variables through a url?

I am trying to have 2 variable values passed in a url, which url will be redirected after. How can I insert them in a JavaScript string?

I have:

var a = document.getElementById("username_a").value;
var b = document.getElementById("username_b").value;

and want something like: var string_url = "http://www.example.com/?{a}blabla={b}" and then redirect somehow.

In PHP I would go with that code for example: <iframe src="http://www.example.com?query=<?php echo $the_variable;?>">

Upvotes: 3

Views: 41235

Answers (3)

Matteo B.
Matteo B.

Reputation: 4064

You can add strings in JavaScript, "a" + "b" == "ab" evaluates to true.

So what you want is probably var string_url = "http://www.example.com/?" + a + "&blabla=" + b;

But you should ever escape vars especially if they come from inputs, so try

a = encodeURIComponent(a);
b = encodeURIComponent(b);

And then

var string_url = "http://www.example.com/?" + a + "&blabla=" + b;

To redirect you can use window.location:

window.location = string_url;

Upvotes: 7

Quentin
Quentin

Reputation: 943108

JavaScript doesn't do string interpolation. You have to concatenate the values.

var uri = "http://example.com/?" + encodeUriComponent(name_of_first_variable) + "=" + encodeUriComponent(value_of_first_variable) + '&' + encodeUriComponent(name_of_second_variable) + "=" + encodeUriComponent(value_of_second_variable);
location.href = uri;

Upvotes: 0

gotofritz
gotofritz

Reputation: 3381

use the ampersand to split vars

var string_url = "http://www.example.com/?" + "username_a=" + a + "&username_b=" + `b

Could be made more sopisticated, but that in essence is what you need

Upvotes: 0

Related Questions