Passing value to JS function through URL on window load - javascript

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>

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);
}

Converting Javascript hashtag

What I'm trying to do is fetch a single piece of a string without using the hashtag element in the url. I already have a functioning code but it needs altering. So, how do I fetch any part of the url after ?.
Say I have ?fx=shipment+toys/fish-fix-fx/ as my url string; I want the button to show if shipment or fish or fx was my choice of selections for example.
Buttons showing with hastag: http://jsfiddle.net/66kCf/2/show/#iphone
Original JSFiddle (buttons not showing): http://jsfiddle.net/66kCf/2/
I want the iPhone buttons to show if fix was my choice: http://jsfiddle.net/66kCf/2/show/?fx=shipment+toys/fish-fix-fx/
try doing it with .split() and.match() like this...
var keys = window.location.href.split('?');
if (keys[1].match(/(fix|fish|fx)/))
{
$("#linkdiv").append(nextLink);
$("#linkdiv1").append(nextLink);
$("#linkdiv2").append(nextLink);
}
demo button showing : http://jsfiddle.net/LbKmf/show/?fx=shipment+toys/fish-fix-fx/
demo button not showing: http://jsfiddle.net/LbKmf/show/?reigel
Is this what your looking for:
"?fx=shipment+toys/fish-fix-fx/".split(/[\?=+\/-]/g);
window.location.search and split into array for comparisons
explained in How can I get a specific parameter from location.search?
http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
Generally, Javascript doesn't have a built-in functionality for query string parameters. You can use string manipulation on window.location.search to get your parameters out of the URL string. Note that location.search includes the ? character too.
Something like this should do:
var queryString = function () {
// Anonymous function - executed immediately
// get rid of the '?' char
var str = "?fx=shipment+toys/fish-fix-fx/";
var query = str.substring(str.lastIndexOf('=')+1,str.indexOf('/'));
var vars = query.split("+");
for (var i=0;i<vars.length;i++){
console.log(vars[i]);
}
return vars;
} ();

html link variable

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.

Appending query strings from multiple pages

I'm currently stumped on this. I've snooped around for a bit and haven't found any concrete answer using just JS to do this, and so my question is thus. If I am navigating multiple pages and want to keep query strings from the one before attached to the url, what is the easiest way to do this?
You can do this if the way the user "navigates" is by using links within the pages.
In a given html page, Javascript running within the page can see the url's query parameters via the window.search property. Mozilla docs.
Then use JS to modify all of the page's anchor elements' href links to add on the already existing query parameters to the links.
Result: clicking on a link in the page will result in the new page having both the existing and new query parameters.
I don't think there is an easy way. You will have to take in account the current query parameters every time you compose a URL or create a form.
Are you asking for this one?
var url1 = "...", url2 = "...";
var query1 = url1.split("#")[0].split("?").slice(1).join("?");
if (!query1)
return url2;
var parts2 = url2.split("#");
parts2[0] += (parts2[0].indexOf("?")>-1 ? "&" : "?" ) + query1;
return parts2.join("#");
This extracts the query string from url1 and appends it to the query string of url2, returning the new url2.

Break a URL into its components

I'm using javascript and would like to take a URL string that I have and break it down into its components such as the host, path, and query arguments.
I need to do this in order to get to one of the query arguments, which is itself a URL and is thus encoded in the original URL string.
I feel like there should be an easy way to do this in Javascript. Perhaps something that looks like this:
var what_I_Want = url("http://www.domain.com?queryArg1=somequeryargument").getQueryArgumentValue("queryArg1");
The parseUri function will do everything you need
Edit
Alternatively you can get the DOM to do the hard work for you and access properties on a newly created a object for different parts of the URL.
<script type="text/javascript" language="javascript">
newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
</script>
Hope this will help..
In javascript you can do this by using split() for the params and using the location object for the protocol and domain -- like Carl suggested
Also you can use parseUri as Tak suggested
There is also a jQuery plugin which makes parsing easier if you are already using jQuery in your project: https://github.com/allmarkedup/jQuery-URL-Parser#readme
Example:
$.url('http://allmarkedup.com?sky=blue&grass=green').param('sky'); // returns 'blue'
Probably not the greatest way of doing it but a simple method to get the query string in JavaScript would be to just use something along the lines of:
a = "http://www.domain.com?queryArg1=somequeryargument";
query = a.substring(a.indexOf('?')+1);
You could then split the query up based on the &'s and again on the = to get at whatever param you need.
Sorry if this ain't very helpful as its a bit of a low tech method :P
EDIT:
Just wrote a quick little JavaScript object to get URL Query parameters for you (sort of like) in your example. Only tested it in chrome but in theory it should work :)
//Quick and dirty query Getter object.
function urlQueryGetter(url){
//array to store params
var qParam = new Array();
//function to get param
this.getParam = function(x){
return qParam[x];
}
//parse url
query = url.substring(url.indexOf('?')+1);
query_items = query.split('&');
for(i=0; i<query_items.length;i++){
s = query_items[i].split('=');
qParam[s[0]] = s[1];
}
}
//Useage
var bla = new urlQueryGetter("http://www.domain.com?queryArg1=somequeryargument&test=cheese");
alert(bla.getParam('test'));

Categories

Resources