Changing how URL parameters are appended to links based on destination - javascript

My company is serving up PPC landing pages with Unbounce (on a subdomain), which then links back to our website. We're using the following code to append the AdWords gclid variable to outgoing links:
$(document).ready(function() {var params = window.location.search.replace(/\+/g,'%20'); var button = $('a').each( function(i) {this.href = this.href + params;});});
The issue arises when the Gclid gets appended to a URL that already has a parameter (like our checkout forms). You end up with a URL that looks like this:
domain.com/checkout?EventID=15546?Gclid=jdkI324kd
I'm wondering if there's a way to change the Glid's '?' to an '&' for certain URLs that already have parameters, while keeping the existing functionality of using the '?' for the others.
Thanks!
Edit: Seems like there's some redirection going on, this is how the href looks for the links in question:
http://domain.com/lp/clkg/https/domain.com/cart.aspx?EventID=125160?gclid=CPfO1JaOx7oCFQZyQgod5A4AFw

Simply replace it yourself:
$(document).ready(function() {
var params = window.location.search.replace(/\+/g,'%20');
var button = $('a').each( function(i) {
if (this.href.indexOf('?') == -1) {
this.href = this.href + params;
} else if (params.length) {
this.href = this.href + '&' + params.substr(1);
}
});
});
Edit: and are you aware that you are replacing subsequent spaces with only one single '%20'?

Related

Retrieve URL Parameters Sent Through JQuery .load()

I am not sure if what I'm trying to do is possible or if I'm going about this the right way. In some circumstances I want them to have a GET parameter as part of the URL. I want the receiving page to be able to differentiate whether the sending load has a parameter or not and adjust accordingly.
Here is what I have that is sending the load:
$(document).ready(function () {
$("a").click(function () {
$("div.pageContent").html('');
$("div.pageContent").load($(this).attr('href'));
return false;
});
});
In this case, the load could have "example.php" or "example.php?key=value". In looking around (primarily on this site), I've found things that seem to be close, but don't quite get there. In the page that is getting loaded (example.php), I have the following:
function $_GET(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];
}
$(document).ready(function () {
var URL = "example2.php";
if ($_GET('key'))
{
URL = "example2.php?key=" + $_GET('key');
URL = URL.split(' ').join('%20');
}
$("div.output").load(URL);
});
If the sending source includes a query string, I want to add that to the URL and load it in a div that is unique to this page, otherwise I want to just load it as is without the query string. The big issue I'm running into (I believe) is since this is coming from an AJAX call, the "window.location.href" is not what was sent from the JQuery but rather the URL of the root page which never changes. Is there a way to be able to know what the full URL is that was sent from the load() in the first page by the second one?
Thank you in advance for your help.
I realized that the GET parameters were getting passed as I could access them through php without issue. I didn't know that I could insert php code into a javascript block but once I tried it, all worked out. My new code looks like this:
$(document).ready(function () {
var URL = "example2.php";
var myValue = "<?php echo $_GET['key']; ?>";
if (myValue !== "")
{
URL = "example2.php?key=" + myValue;
URL = URL.split(' ').join('%20');
}
$("div.output").load(URL);
});
I was able to get rid of the GET function out of javascript entirely. I probably made this much more difficult from the start but hopefully it can help someone else in the future.

Add language suffix to url if it doesn't exist already (javascript)

I have a multi language site and people come in via links WITH a url suffix (/lang/en for instance) or WITHOUT a suffix (just the page url).
Now I want to create the language switch function with a link (with a class to trigger the javascript).
My link class will be "english" for instance and in the JS I first need to check if there isn't a language suffix to the url already before I append it.
Here's what I have right now (from another thread):
<a class="english" href="">English</a>
<script>
$('.datalink').attr('href', function() {
return this.href + '/lang/en';
});
</script>
This adds the suffix but Without checking if it already exists, how do I check if it is already there and not append it? or change it to another language (/lang/nl)?
UPDATE
Actually my class is not on the href but on the <li> around it, it looks like:
<li class="english"><a title="English">English</a></li>
so now I have
$('.english >a').attr('href', function() {
var suffix = this.href.match(/lang\/en\/?$/i) ? "" : "/lang/en";
return this.href + suffix;
});
NOTE Wat I want to achieve is two links on each page of my website that will consist of the basic page url with a
lang/en
or
lang/nl
suffix to them. When clicked those links will load the same page but with the language suffix in the url, my language plugin will pick that up an present the language.
You can use a regular expression to check if the URL contains the suffix:
if (this.href.match(/lang\/en\/?$/i)) {
/* CONTAINS THE SUFFIX */
} else {
/* DOESN'T CONTAIN IT */
}
The way that I'd probably do it is as follows:
$('.datalink').attr('href', function() {
// suffix is blank if the URL already contains the language portion
var suffix = this.href.match(/lang\/en\/?$/i) ? "" : "/lang/en";
return this.href + suffix;
});
Somehow the none of the above javascript worked for me, I don't know what I was doing wrong but finayl I decided to resort to php cause I understand that much better. I use this on a wordpress site and I came up with the following code (in theme functions.php) that worked for me:
// add languages to menu
add_filter('wp_nav_menu_items','add_langs', 10, 2);
function add_langs($items, $args)
{
if( $args->theme_location == 'primary-menu')
$current_url = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$href = str_replace(array('/lang/en','/lang/nl'),'',$current_url);
$english = '<li class="english">EN</li>';
$nederlands = '<li class="nederlands">NL</li>';
return $items . $english . $nederlands ;
}
This finds my menu called "primary-menu" and adds two items to this menu consisting of $english and $nederlands links.
I had to get the page url with $_server['HTTP_HOST'] instead of get_permalink() cause that one returned a random url somehow. the first one always works and with the str_replace I replace the language additions first if they exist (str_replace doesn't need an if statement, it always checks if it exists before replacing)
Hope this helps someone else out, still wondering why the javascript didn't work for me!
if it is a suffix that always starts with /lang, try this
Live Demo
$('.english a').each(function() {
$(this).attr('href', this.href.split("/lang")[0] + '/lang/en');
});
or if you want to keep one if there
$('.english a').each(function() {
var href = this.href;
var pos = href.indexOf("/lang/");
if (pos == -1) $(this).attr('href', href.substring(0,pos)+'/lang/en');
});

Creating email link with dynamically generated body with html5 & javascript

Am trying to create a link to create an email to send information to the user, the body of which needs to be filled with data generated by a javascript function, and hope that someone can help.
Idealy, if I could substitute the 'body_blurb' below, with a string returned from a javascript function called at the time of clicking that'd be perfect.
e-mail data
Appreciate your time
I just assigned an id to the link here, but you could create something more generic if you wanted. Once you have an onclick handler created you can access the url with href. Set this to whatever you want.
http://jsfiddle.net/f3ZZL/1
var link = document.getElementById('email');
link.onclick = function() {
this.href = "mailto:you#yourdomain.com?subject=Data&body=";
this.href += getBody();
};
function getBody() {
return 'HelloWorld';
}
Here is the no-spam method
var link = document.getElementById('email');
link.onclick = function() {
var name = "you";
var domain = "yourdomain.com";
var linker = "mailto:" + name + '#' + domain + "?subject=Data&body=";
linker += getBody();
link.setAttribute("href", linker);
};
function getBody() {
return 'HelloWorld';
}
On Fiddle
You don't actually need to set the href value. What you're really trying to do is send the browser to a mailto: URL: the href is just a means to that end.
Leave the href blank and make the link have an onClick handler. In the onClick, feed the browser the mailto: URL (after you build it using your variable). Presto, done.

Rewriting Links with Javascript

I have a few hyperlinks like this on my page
Link
When there is a query string in the address, example: mydomain.com?r=abcd the hyperlink should change to Link
I want the same thing to happen to "rh" query argument also. ie, when someone goes to mydomain.com?rh=abcd
This Link
should change to Link
Basically the script should say: if the queries "r" and "rh" is not null, the links with the class=rewrite must be changed. Everything after the "?" must be removed & the query string in the address should be added to the hyperlinks.
change the domain:
var newurl = 'http://testdomain.com';
$('a').each(function(I,EL){
var url = $(EL).attr('href');
if(url.indexOf('?')>= 0){
url = url.split('?');
url = newurl + url[1];
$(EL).attr('href', url);
}
}

Create and go to url with Javascript

I want to be able to produce a URL based on certain properties and then go to the new URL in javascript.
Here is what I have so far:
triggerNumber = document.findcontrol(txtTrigNo).text;
hostAddress= top.location.host.toString();
url = "http://" + hostAddress "/" + triggerNumber
How do I navigate to the new URL?
Simply try:
window.location = url;
But before trying to do that, you have to make sure the page at the address "http://" + hostAddress "/" + triggerNumber exists. For example by putting valid triggerNumbers in an array and check if it exists or not. So:
//Not sure if at the end it should be .text or .value or .value()
triggerNumber = document.findcontrol(txtTrigNo).text;
var validTriggers = [123, 456, 789];
if (validTriggers.indexOf(parseInt(triggerNumber)) == -1) {
alert("Invalid trigger number");
} else {
hostAddress= top.location.host.toString();
url = "http://" + hostAddress "/" + triggerNumber;
}
Finally, if the destination is a server-side page (php, asp, etc), the address usually looks like this:
"http://" + hostAddress "/trigger.php?id=" + triggerNumber;
but you'd better use forms for this.
Edit: As Cerbrus suggested, validating the values with javascript is a good way to tell the user about his errors before navigating away from the page. But to make sure the correct data is sent to server, it is important to do the validation in the server-side code, too.
In this example, in case of an invalid trigger number the user may finally see a 404 error; but with sensitive information worse things can happen.
What you need is:
document.location.href = url;
After you have the URL in the url variable.
To get value of input element have:
var triggerNumber = document.getElementById("txtTrigNo").value;
This will get the hostname and port of the server, and concatenate the value of the element onto the end, and then go to the resulting URL.
var triggerNumber = document.getElementById("txtTrigNo").value();
var url = "http://"+window.location.host+"/"+triggerNumber;
window.location = url;

Categories