html link variable - javascript

Is it possible to pass two variables through to another html page through a link?
For example... I have a directory page where when a user clicks a store link, it links to another html page with the map centered on the specific store. The function that centers the map on the store takes two variables, storeID, storeName. There are hundreds of stores and currently I would have to manually create each store page separately by hardcoding those two variables so that each page loads slightly differently. Is there a way to pass these two variables with a link, to avoid many different html pages?
Perhaps something along the lines of <a href "thisPage.html", var1, var2>?
ex. code
thispage.html
var1;
var2;
function myFunc(var1, var2) {
~~~
}

Not like that, but you can use URL parameters.
thisPage.html?var1=foo&var2=bar
Then you can read them on the second page. I like to use this function for that:
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
From http://www.netlobo.com/url_query_string_javascript.html
So on your second page, you can just do gup("var1") and you will get foo.

Use a query string.
In a URL a ? indicates the start of the query. It consists of a series of key=value pairs separated by & characters.
The encodeURIComponent function will escape text for inserting as a key or a value.
You can then assign it to the href attribute of the link element or set location.href to it.

Related

Custom Javascript GTM variable - remove UTMs

I've got a CSJ variable to capture the last parameter of the URL. Given I'm interested on capturing the location and its position may vary (see example below), I managed to create a custom variable that will always give me the last parameter in the URL.
URL examples:
https://www.example.co.nz/location/**holmwood**
https://www.example.co.nz/find-a-location/auckland/**central-auckland**
The issue I'm having is that my script (see below) is not only capturing the last parameter of the URL, but any string after the "?" symbol, which are mainly UTMs.
Code:
function(){
var pageUrl = window.location.href;
return pageUrl.split("/")[pageUrl.split("/").length - 1];
}
So, on my GA view instead of seeing the ph + the location, I see a large string:
I know I could use page path and remove query from there, but for a specific event I'd rather sort that out from the custom variable because of the type of value I'm passing.
What else should I add to my script to keep it completely the same and exclude any query parameters that might be automatically tagged?
Thanks.
Rather than returning the first split, I would then put it through an additional one where you are splitting on the '?'
function(){
var pageUrl = window.location.href;
var lastSlash = pageUrl.split("/")[pageUrl.split("/").length - 1];
return lastSlash.split("?",1);
}

Passing Javascript Variable to second html page and show [duplicate]

I have two pages - "page 1" and "page 2". On page 1 there's an text-box with a value of e.g. 100 and a button at the end.
By pressing the button I want javascript to save the value of the textbox in a global (?) variable and jump to page 2. With "window.onload" I want a second Javascript-function to alert the value saved at page1.
Here's my Javascript code:
<script type="text/javascript">
var price; //declare outside the function = global variable ?
function save_price(){
alert("started_1"); //just for information
price = document.getElementById('the_id_of_the_textbox').value;
alert(price); //just for information
}
<script type="text/javascript">
function read_price(){
alert("started_2");
alert(price);
}
On "page 1" I have this send-Button with:
<input class="button_send" id="button_send" type="submit" value="Submit_price" onclick="save_price();"/>
It starts the Javascript function and redirects me correctly to my page2.
But with this ont the second page:
window.onload=read_price();
I always get an "undefined" value of the global variable price.
I've read a lot about those global variables. E.g. at this page: Problem with global variable.. But I can't get it working...
Why is this not working?
Without reading your code but just your scenario, I would solve by using localStorage.
Here's an example, I'll use prompt() for short.
On page1:
window.onload = function() {
var getInput = prompt("Hey type something here: ");
localStorage.setItem("storageName",getInput);
}
On page2:
window.onload = alert(localStorage.getItem("storageName"));
You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.
Your best option here, is to use the Query String to 'send' the value.
how to get query string value using javascript
So page 1 redirects to page2.html?someValue=ABC
Page 2 can then
read the query string and specifically the key 'someValue'
If this is anything more than a learning exercise you may want to consider the security implications of this though.
Global variables wont help you here as once the page is re-loaded they are destroyed.
You have a few different options:
you can use a SPA router like SammyJS, or Angularjs and ui-router, so your pages are stateful.
use sessionStorage to store your state.
store the values on the URL hash.
To do this, I recommend sending data within the link data. This is a very simple way of doing it without PHP. Simply get the link in the second page and replace the previous link with "".
Page_One.html:
<script>
//Data to be transfered
var data = "HelloWorld";
//Redirect the user
location.replace("http://example.com/Page_Two.html?" + data);
</script>
Page_Two.html :
<script>
//Get the current link
var link = window.location.href;
//Replace all content before ? with ""
link = link.replace("http://example.com/Page_Two.html?","");
//Display content
document.write("Page_One.html contains:" + link + "");
</script>
Hope it helps!
I have a simple Approach rather (Pure JS):
Page One :
Goto Your Info
Note : You've to encode your GTK value (i.e parameter value) in Base64
Next is Page TWO :
<script>
// first we get current URL (web page address in browser)
var dloc= window.location.href;
//then we split into chunks array
var dsplt= dloc.split("?");
//then we again split into final chunk array, but only second element
//of the first array i.e dsplt[1]
var sanitize= dsplt[1].split("=");
// now here comes the tricky part, join all elements into single //string. IT may be the case, that base64 string contain '=' sign, we shall find it
var dlen= sanitize.length;
var FinString= "";
// we will start from 1, bcoz first element is GTK the key we don't // want it
for(i=1;i<dlen;i++)
{
FinString= FinString+sanitize[i];
}
// afterwards, all the Base64 value will be ONE value.
// now we will convert this to Normal Text
var cleantxt= window.atob(FinString);
document.getElementById("yourname").innerHTML= "Your Name is : <b>"+cleantxt+" .";
You can do anything with the parameter decoded info... Like Redirecting visitor
immediately to another page thru a "POST" method form automatically submitted
by Javasript to Lead a php page finally, without an visible parameters, but with
invisible hidden parms.

How to make a JS variable cross over HTML pages? [duplicate]

I have two pages - "page 1" and "page 2". On page 1 there's an text-box with a value of e.g. 100 and a button at the end.
By pressing the button I want javascript to save the value of the textbox in a global (?) variable and jump to page 2. With "window.onload" I want a second Javascript-function to alert the value saved at page1.
Here's my Javascript code:
<script type="text/javascript">
var price; //declare outside the function = global variable ?
function save_price(){
alert("started_1"); //just for information
price = document.getElementById('the_id_of_the_textbox').value;
alert(price); //just for information
}
<script type="text/javascript">
function read_price(){
alert("started_2");
alert(price);
}
On "page 1" I have this send-Button with:
<input class="button_send" id="button_send" type="submit" value="Submit_price" onclick="save_price();"/>
It starts the Javascript function and redirects me correctly to my page2.
But with this ont the second page:
window.onload=read_price();
I always get an "undefined" value of the global variable price.
I've read a lot about those global variables. E.g. at this page: Problem with global variable.. But I can't get it working...
Why is this not working?
Without reading your code but just your scenario, I would solve by using localStorage.
Here's an example, I'll use prompt() for short.
On page1:
window.onload = function() {
var getInput = prompt("Hey type something here: ");
localStorage.setItem("storageName",getInput);
}
On page2:
window.onload = alert(localStorage.getItem("storageName"));
You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.
Your best option here, is to use the Query String to 'send' the value.
how to get query string value using javascript
So page 1 redirects to page2.html?someValue=ABC
Page 2 can then
read the query string and specifically the key 'someValue'
If this is anything more than a learning exercise you may want to consider the security implications of this though.
Global variables wont help you here as once the page is re-loaded they are destroyed.
You have a few different options:
you can use a SPA router like SammyJS, or Angularjs and ui-router, so your pages are stateful.
use sessionStorage to store your state.
store the values on the URL hash.
To do this, I recommend sending data within the link data. This is a very simple way of doing it without PHP. Simply get the link in the second page and replace the previous link with "".
Page_One.html:
<script>
//Data to be transfered
var data = "HelloWorld";
//Redirect the user
location.replace("http://example.com/Page_Two.html?" + data);
</script>
Page_Two.html :
<script>
//Get the current link
var link = window.location.href;
//Replace all content before ? with ""
link = link.replace("http://example.com/Page_Two.html?","");
//Display content
document.write("Page_One.html contains:" + link + "");
</script>
Hope it helps!
I have a simple Approach rather (Pure JS):
Page One :
Goto Your Info
Note : You've to encode your GTK value (i.e parameter value) in Base64
Next is Page TWO :
<script>
// first we get current URL (web page address in browser)
var dloc= window.location.href;
//then we split into chunks array
var dsplt= dloc.split("?");
//then we again split into final chunk array, but only second element
//of the first array i.e dsplt[1]
var sanitize= dsplt[1].split("=");
// now here comes the tricky part, join all elements into single //string. IT may be the case, that base64 string contain '=' sign, we shall find it
var dlen= sanitize.length;
var FinString= "";
// we will start from 1, bcoz first element is GTK the key we don't // want it
for(i=1;i<dlen;i++)
{
FinString= FinString+sanitize[i];
}
// afterwards, all the Base64 value will be ONE value.
// now we will convert this to Normal Text
var cleantxt= window.atob(FinString);
document.getElementById("yourname").innerHTML= "Your Name is : <b>"+cleantxt+" .";
You can do anything with the parameter decoded info... Like Redirecting visitor
immediately to another page thru a "POST" method form automatically submitted
by Javasript to Lead a php page finally, without an visible parameters, but with
invisible hidden parms.

Replacing two elements in a URL in javascript

Bit of a javascript newbie so not sure if this question is easy or impossible.
Am working on a site with different testing environments and have made a greasemonkey script to make a set of buttons to switch from one to another:
if (/^(.*?)\www.mysite.com(.*)$/.test(document.location.href)) {
document.location.href = RegExp.$1+"iww1.mysite.com"+RegExp.$2
}
This has been working except for some URLs have a search string ID that also needs changing to a different number too.
&storeId=15162
I feel like I've exhausted my limited knowledge, by adding another if function within the {} to adding various replace functions, all to no avail.
If this makes sense and anyone can help it would be much appreciated.
Cheers
Your first problem is that the location object is magical: assigning to it, or to any of its properties, causes the browser to navigate to the assigned URL. Since this will typically stop your script, you won't be able to do it twice. Instead, you should store the intermediate URL in some other variable, and only assign it back to location.href once you're ready to move to the new page.
Also, you didn't specify how the new "search string ID" should be calculated, so I just assumed that you have some function, named e.g. getNewStoreID(), that will return the new ID when you give it the old one. Given such a function, this code should do it:
var siteRegExp = /www\.mysite\.com/;
var paramRegExp = /([?&]storeId)=(\d+)/;
if ( siteRegExp.test( location.href ) ) {
var href = location.href.replace( siteRegExp, "iww1.mysite.com" );
var match = paramRegExp.exec( href );
if ( match ) {
href = href.replace( paramRegExp, "$1=" + getNewStoreID( match[2] ) );
}
location.href = href; // navigate to the new URL!
}

Passing value to JS function through URL on window load

my page http://www.dinomuhic.com/2010/index.php loads the Showreel at the start of the page using an onLoad call in body like this:
<body onLoad="sndReq('96')">
96 is the ID of the showreel in the SQL Library.
The JS function "sndReq" is an AJAX call using JQuery which opens the requested item and displays it in the main window.
Now my question: What if I want to send a link to a client which opens a specific item directly so he does not have to navigate through the site?
Something like http://www.dinomuhic.com/2010/index.php?sndReq=234 (which of course doesn't work now and just opens the showreel, probably because the onLoad in the body tag overrides it)
How can I implement this? I want to be able to open specific items by URL but if nothing is passed through the URL it should always open item 96.
Thank you in advance. I'm sure its pretty easy I just can't see it.
Cletus
You need to parse the query string. I find the easiest way to deal with the query string is to do the following. First, you need to extract the query string from the URL:
var queryStr = window.location.search; // will give you ?sndReq=234
Then, you can strip out the ? and split each query string parameter into an array:
var paramPairs = queryStr.substr(1).split('&');
Now you can build a hash table object of the name/value pairs making up the query string:
var params = {};
for (var i = 0; i < paramPairs.length; i++) {
var parts = paramPairs[i].split('=');
params[parts[0]] = parts[1];
}
In your onload, you can now use the parameter thusly:
sndReq(params.sndReq);
Make sure that the code is run within a script in the head of your document so that it's computed before the onload is executed.
if you are using jQuery, why not use the DOM-ready handler instead of onload ? on that note, if it's just an ajax request, you don't even need to wait for DOM-ready. if you parse the query, you should be able to pass that in to your existing function.
// Wait for DOM-ready, may not be needed if you are just
// making a request, up to you to decide :)
$(function() {
// window.location.search represents the query string for
// current URL, including the leading '?', so strip it off.
var query = window.location.search.replace(/^\?/, "");
// If there is no query, default to '96'
if ( !query ) {
query = '96';
}
// Call existing function, passing the query value
sndReq( query );
});
hope that helps! cheers.
You can use RegExp to accomplish this, read the url parameters and pass them to ajax.
this simple script will read the current url and pass through regex to filter for paramters you specify.
EG: ThisReq = gip('sndReq'); pulls sndReq and value from the url.
<script language="javascript">
function gip(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
sndReq('96');
else
return results[1];
}
// parameter pulled from url.
ThisReq = gip('sndReq');
// executes function sndReq();
sndReq(''+ThisReq+'');
</script>

Categories

Resources