I would like to automatically add an affiliate identifier to URLs on my website.
For example, I have external URLs such as:
https://www.adairs.com.au/
https://bedthreads.com.au/products/caitlin-robson-footed-bowl
My affiliate identifier varies based on the retailer, such as:
adairs.com.au: https://t.example.com/12345/t/54321?Url=
bedthreads.com.au: https://t.example.com/12121/t/21212?Url=
I need these automatically prepended at the beginning of the external URLs upon click to form:
https://t.example.com/12345/t/54321?Url=https://www.adairs.com.au/
https://t.example.com/12121/t/21212?Url=https://bedthreads.com.au/products/caitlin-robson-footed-bowl
The closest solution I have found was here however I am not very experienced in java and was unable to make it work. Ideally, I would also like to add other automatic affiliate identifiers for other retails in future.
Also, is it possible to add this in PHP?
Any help would be greatly appreciated. Thank you.
// attach a click even to all <a> elements
$("a").click(function() {
addAffiliate(this);
});
// adairs affiliate URL for redirect
var adairsaffURL = "https://t.example.com/12345/t/54321?Url=";
// bedthreads affiliate URL for redirect
var bedthreadsaffURL = "https://t.example.com/12121/t/21212?Url=";
// function called when link is clicked
function addAffiliate(link) {
// make sure this link is not to the current site and does not contain the affiliateURL
if ((link.href).indexOf(adairs.com.au) < 0 && (link.href).indexOf(adairsaffURL) < 0){
// update the link with the affiliateURL, the url encoded link, and the additional query string
link.href = affiliateURL + escape(link.href);
}else if((link.href).indexOf(bedthreads.com.au) < 0 && (link.href).indexOf(bedthreadsaffURL) < 0){
link.href = bedthreadsaffURL + escape(link.href);
}
alert(link.href);
// return true to follow the link
return true;
}
As your idea, I updated your code to let it works. Please Run code snippet to see the demo.
You just need to use .indexOf('adairs.com.au') to check the link belongs to the affiliate program, so you append it into affiliate URL.
jQuery(document).ready(function($) {
// adairs affiliate URL for redirect
var adairsaffURL = "https://t.example.com/12345/t/54321?Url=";
// bedthreads affiliate URL for redirect
var bedthreadsaffURL = "https://t.example.com/12121/t/21212?Url=";
// function called when link is clicked
addAffiliate = function(link) {
if (link.hash.substr(1).length > 0) return true;
var redirectUrl = link.href;
if (!redirectUrl || !isValidURL(redirectUrl)) return true;
if (redirectUrl.indexOf('adairs.com.au') > 0) {
redirectUrl = adairsaffURL + escape(redirectUrl);
} else if (redirectUrl.indexOf('bedthreads.com.au') > 0) {
redirectUrl = bedthreadsaffURL + escape(redirectUrl);
}
link.href = redirectUrl;
return true;
}
$("a").click(function(event) {
addAffiliate(this);
});
function isValidURL(string) {
var res = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*)/g);
return (res !== null)
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
test adairs
<br/><br/>
test bed threads
<br/><br/>
test not match adairs or bedthreads
<br/><br/>
test no link
Update: function to add to Wordpress. Put the below into your functions.php in your theme.
add_action('wp_footer', 'auto_affiliate_url');
function auto_affiliate_url()
{
?>
<script>
jQuery(document).ready(function ($) {
// adairs affiliate URL for redirect
var adairsaffURL = "https://t.example.com/12345/t/54321?Url=";
// bedthreads affiliate URL for redirect
var bedthreadsaffURL = "https://t.example.com/12121/t/21212?Url=";
// function called when link is clicked
addAffiliate = function(link) {
if (link.hash.substr(1).length > 0) return true;
var redirectUrl = link.href;
if (!redirectUrl || !isValidURL(redirectUrl)) return true;
if (redirectUrl.indexOf('adairs.com.au') > 0) {
redirectUrl = adairsaffURL + escape(redirectUrl);
} else if (redirectUrl.indexOf('bedthreads.com.au') > 0) {
redirectUrl = bedthreadsaffURL + escape(redirectUrl);
}
link.href = redirectUrl;
return true;
}
$("a").click(function(event) {
addAffiliate(this);
});
function isValidURL(string) {
var res = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*)/g);
return (res !== null)
};
});
</script>
<?php
}
Related
I'm trying to reuse a button in different landing pages and change the hyperlink of this button depending on what page is being browsed.
I started my function for it but I'm stuck on how to pass the data. If the user is on a page that contains home_ns in the url, I would like the button link to be cart1 and if the user is on a page called home_nd I would like it to be cart 2.
<script type="text/javascript">
var cart1 = '/?add-to-cart=2419';
var cart2 = '/?add-to-cart=2417';
function urlCart() {
if(window.location.href.indexOf("home_ns") > -1) {
// This is where I am stuck
}
}
</script>
Then the button will be
<button onclick="urlCart()">Order Now</button>
Here is what you need:
var cart1 = '/?add-to-cart=2419';
var cart2 = '/?add-to-cart=2417';
function urlCart() {
if(window.location.href.indexOf("home_ns") > -1) {
window.location.href = cart1;
} else {
window.location.href = cart2;
}
}
You could create a look-up map of pages to cart ID. You can then update the search parameter in the URL to reflect the found ID.
Note: Since the Stack snippet below is not going to actually have the correct href, the code will not add/update the parameter. If you want to integrate this, replace the url variable declaration with this:
let url = window.location.href;
You could also use the pathname instead of the href for finer granularity.
let url = window.location.pathname;
// See: https://stackoverflow.com/a/56593312/1762224
const setSearchParam = function(key, value) {
if (!window.history.pushState) return;
if (!key) return;
let url = new URL(window.location.href);
let params = new window.URLSearchParams(window.location.search);
if (value === undefined || value === null) params.delete(key);
else params.set(key, value);
url.search = params;
url = url.toString();
window.history.replaceState({ url: url }, null, url);
}
const pageMap = {
"home_ns": 2419,
"home_nd": 2417
};
function urlCart() {
let url = 'https://mywebsite.com/home_ns' || window.location.href;
Object.keys(pageMap).some(page => {
if (url.includes(page)) {
console.log('Found page:', page);
setSearchParam('add-to-cart', pageMap[page]);
return true;
} else {
return false;
}
});
}
<button onclick="urlCart()">Order Now</button>
Simply you can move the user to another page by:
location.href = myURL;
The browser will automatically go to the specified page.
Examples of what a URL can be:
An absolute URL - points to another web site (like
location.href="http://www.example.com/default.htm")
A relative URL - points to a file within a web site (like location.href="default.htm")
An anchor URL - points to an anchor within a page (like
location.href="#top")
A new protocol - specifies a different protocol
(like location.href="ftp://someftpserver.com",
location.href="mailto:someone#example.com" or
location.href="file://host/path/example.txt")
Source
I am using a javascript form script and I want to redirect to an external website. I set the redirect to www.paypal.me but it actually redirects the user to www.mysite.com/www.paypal.me
How can I edit the code below to instead redirect the user to the actual site, not prefaced by my own URL?
var redirect = "www.paypal.me";
...
this.submitOK = function(){
if( redirect == '' ){
showThankYouMessage();
return;
};
try{
if( parent ) parent.location.href = redirect;
}catch(e){
location.href = redirect;
};
}
}
Here you can find a small overview over the redirect methods in js: https://appendto.com/2016/04/javascript-redirect-how-to-redirect-a-web-page-with-javascript/
To a redirect use something like this:
<script>
var locationn = "https://google.com";
window.location = locationn;
I'm would like to do a 2 step process without the user knowing. Right now when the user click on the link from another page.
URL redirect to run some JavaScript function that updates the database.
Then pass the variable to view a document.
User clicks on this link from another page
Here is some of code in the JavaScript file:
<script type="text/javascript">
window.onload = function(){
var auditObject ="";
var audit_rec = {};
var redirLink = "";
if(document.URL.indexOf('?1w') > -1 {
redirLink = "https://www.wikipedia.org/";
auditObject = redirLink;
audit_rec.action = "OPEN";
audit_rec.object = auditObject;
audit_rec.object_type = "WINDOW";
audit_rec.status = "Y";
window.open(redirLink);
} else {
audit_rec.target = /MyServlet;
audit_rec.action = "OPEN";
audit_rec.object = TESTSITE;
audit_rec.object_type = "WINDOW";
audit_rec.status = "Y";
}
function audit(audit_rec) {
var strObject = audit_rec.object;
strObject = strObject.toLowerCase();
var strCategory = "";
if (strObject.indexOf("wiki") > -1) {
strCategory = "Wiki";
} else if strObject.indexOf("test") > -1) {
strCategory = "TEST Home Page";
}
//Send jQuery AJAX request to audit the user event.
$.post(audit_rec.target, {
ACTION_DATE : String(Date.now()),
DOMAIN : "TESTSITE",
ACTION : audit_rec.action,
OBJECT : audit_rec.object,
OBJECT_TYPE : audit_rec.object_type,
STATUS : audit_rec.status
});
}
//TEST initial page load.
audit(audit_rec);
}
</script>
Can someone help? Thanks
You could give your link a class or ID such as
<a id="doclink" href="http://website.com/docviewer.html?docId=ABC%2Fguide%3A%2F%2F'||i.guide||'">'||i.docno||'</a>
then use javascript to intercept it and run your ajax script to update the database. Here's how you'd do it in jQuery:
$('#doclink').click(function(e) {
var linkToFollow = $(this).attr('href');
e.preventDefault();
yourAjaxFunction(parameters, function() {
location.href = linkToFollow;
});
});
where the function containing the redirect is a callback function after your ajax script completes. This stops the link from being followed until you've run your ajax script.
if your question is to hide the parameters Here is the Answer
you just use input type as hidden the code like this
'||i.docno||'
I need to fire piece of jQuery code only if it is home page.
URL probability are
http://www.example.com
http://www.example.com/
http://www.example.com/default.aspx
How can i run code if it is any of the above url i can use
var currenturl = window.location
but then i have to change this every time i move my code to server as on local host my url is like
http://localhost:90/virtualDir/default.aspx
in asp.net we can get the it using various
HttpContext.Current.Request.Url.AbsolutePath
or
HttpContext.Current.Request.ApplicationPath
I am not sure what are the equivalent in jQuery
reference of asp.net example
UPDATE:
I have taken a simple approach as i could not find other easy way of doing it
var _href = $(location).attr('href').toLowerCase()
var _option1 = 'http://localhost:51407/virtualDir/Default.aspx';
var _option2 = 'http://www.example.com/Default.aspx';
var _option3 = 'http://www.example.com/';
if (_href == _option1.toLowerCase() || _href == _option2.toLowerCase() || _href == _option3.toLowerCase()) {
$(".bar-height").css("min-height", "689px");
// alert('aa');
}
else
{ //alert('bb'); }
Could you only include the script on the page where it's needed? i.e. only use <script type="text/javascript" src="homepage.js"></script> from default.aspx ?
If not, then, as dfsq said - use window.location.pathname .
var page = window.location.pathname;
if(page == '/' || page == '/default.aspx'){
// -- do stuff
}
You could just get the part after the last slash, to account for folder differences...
var page = window.location.toString();
page = page.substring(page.lastIndexOf('/'));
... but this would be true for both example.com/default.aspx and example.com/folder1/default.aspx.
Remember, this Javascript is client-side, so there's no equivalent to the C# example you linked.
You could use my approch to know exactly the page (also with urlrouting) to use it in javascript:
I use the body id to identify the page.
javascript code:
$(document).ready(function () {
if (document.body.id.indexOf('defaultPage') == 0) {
/*do something*/
}
});
Asp.net code:
in masterpage or page (aspx):
...
<body id="<%=BodyId %>">
...
code behind:
private string _bodyId;
public string BodyId
{
get
{
if (string.IsNullOrWhiteSpace(_bodyId))
{
var path = GetRealPagePath().TrimStart('/','~');
int index = path.LastIndexOf('.');
if (index > -1)
{
path = path.Substring(0, index);
}
_bodyId = path.Replace("/", "_").ToLower();
}
return string.Concat(_bodyId,"Page");
}
}
public string GetRealPagePath()
{
string rtn = Request.Path;
if (Page.RouteData != null && Page.RouteData.RouteHandler!= null)
{
try
{
if (Page.RouteData.RouteHandler.GetType() == typeof(PageRouteHandler))
{
rtn=((PageRouteHandler)Page.RouteData.RouteHandler).VirtualPath;
}
else
{
rtn = Page.Request.AppRelativeCurrentExecutionFilePath;
}
}
catch (Exception ex)
{
Logger.Error(string.Format("GetRealPagePath() Request.Path:{0} Page.Request.AppRelativeCurrentExecutionFilePath:{1}", Request.Path, rtn), ex);
}
}
return rtn;
}
I have a script that specifices that a certain element does not be shown when on a specific page. Below is the code I used:
<script type="text/javascript">
function callOnPageLoad()
{
var url = window.location.href;
if(url == "http://www.exampledomain.com")
{
document.getElementById('rolex').style.display = 'none';
}
}
</script>
However I need to put a few more url's in the if statement, what is the right way of doing this?
Many thanks
I preffer to generate associative array and then check if string is set. It can be obtained from AJAX, from different script etc. and isn't hradcoded into if
<script type="text/javascript">
var urlArray = { "http://www.exampledomain.com" : true, "http://www.exampledomain.com/foobar.html" : true };
function callOnPageLoad()
{
var url = window.location.href;
if( urlArray[url] )
{
document.getElementById('rolex').style.display = 'none';
}
}
</script>
if(url == "http://www.exampledomain.com" || url == "http://www.anotherdomain.com")
{
}
Add more conditions in the if block:
<script type="text/javascript">
function callOnPageLoad()
{
var url = window.location.href;
if(url == "http://www.exampledomain.com" || url == "anotherurl" || url == "andanother")
{
document.getElementById('rolex').style.display = 'none';
}
}
</script>
have an array of urls and iterate
function callOnPageLoad()
{
var urls = [
"http://www.exampledomain.com",
"http://www.exampledomain2.com"
];
var url = window.location.href;
for ( var i=0; i < urls.length; i++ ) {
if(url == urls[i])
{
document.getElementById('rolex').style.display = 'none';
break;
}
}
}
you can create an array of those urls and run for loop thought them, this will be more dynamic approach to your problem.
using long if statements is not advisible because you can loose a character here or a bit of logic there
If your urls point to external urls or match other patterns that you can distinguish them from other urls you can use it without an array.
function callOnPageLoad(type)
{
var url = window.location.href;
var urls=new array("http://www.exampledomain1com","http://www.exampledomain2.com");
if(url in urls){
document.getElementById('rolex').style.display = 'none';
}
}
if(url == "http://www.exampledomain.com" || url =="http://www.url2.com" || url == "http://www.url3.com") and so forth ... ?