Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;?>">

like image 362
a.litis Avatar asked Nov 17 '25 06:11

a.litis


1 Answers

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;
like image 55
Matmarbon Avatar answered Nov 19 '25 20:11

Matmarbon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!