Is there a way to pass javascript variables to url?

Is there a way to make a below script pass javascript values ​​to the href link url?

<script type="text/javascript"> function geoPreview(lat,long) { var elemA = document.getElementById("lat").value; var elemB = document.getElementById("long").value; window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=elemA&lon=elemB&setLatLon=Set"; } </script> 
+10
javascript url
source share
5 answers

Try the following:

  window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+elemA+"&lon="+elemB+"&setLatLon=Set"; 

To put a variable in a string, enclose the variable in quotation marks and append characters as follows:

 var myname = "BOB"; var mystring = "Hi there "+myname+"!"; 

Just remember one rule!

+32
source share

Do you mean to include javascript variable values ​​in the URL query string?

Yes:

  window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+var1+"&lon="+var2+"&setLatLon="+varEtc; 
+3
source share

Summary

Using either string concatenation or string interpolation (via template literals ).

Here with the JavaScript template literal:

 function geoPreview() { var lat = document.getElementById("lat").value; var long = document.getElementById("long").value; window.location.href = 'http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=${lat}&lon=${long}&setLatLon=Set'; } 

Both parameters are not used and can be deleted.

remarks

String concatenation

Attach strings using the + operator:

 window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=" + elemA + "&lon=" + elemB + "&setLatLon=Set"; 

String interpolation

For more concise code, use JavaScript template literals to replace expressions with their string representations. Pattern letters are enclosed in '' and placeholders surrounded by ${} :

 window.location.href = 'http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=${elemA}&lon=${elemB}&setLatLon=Set'; 

Template literals are available since ECMAScript 2015 (ES6).

+1
source share

Try this:

 window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=\''+elemA+'\'&lon=\''+elemB+'\'&setLatLon=Set"; 
-one
source share

It is quite complicated, but it makes sense for an inexperienced programmer. You can include the "#" sign in the URL, and everything else can go after that, simply by going to this page. So you can use JS:

 var pass = prompt("what do you want to pass") var site = "https://google.com" var readysite = site + pass document.location.replace(readysite) 

Then, on another page, use JavaScript to read the URL and get the necessary information.

NOTE: JS above is not verified.

-one
source share

All Articles