How to switch url with javascript button - javascript

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

Related

Automatically prepend affiliate identifier to URLs

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
}

Javascript redirect - remove parent location

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;

How to redirect to the base URL if the given URL ends with a slash?

I have this link http://localhost:3007/sellers-toolkit/, but the right page is only the one without a trailing slash. So I would like a redirection to http://localhost:3007/sellers-toolkit.
I tried to write this part in JavaScript, but it just makes the page reload and nothing happens. What is the right way to achieve this behavior?
var url = "http://localhost:3007/sellers-toolkit/";
if (url) {
url = "http://localhost:3007/sellers-toolkit";
window.location.href = url;
}
my solution for this issue is that i was trying to do that on the javascript side but i found that i have to do this on my node server side.
i used this code:
if (req.url == '/sellers-toolkit' || req.url == '/sellers-toolkit/' ) {
category = 'Selling Privately';
}
Try like below:
var url = "http://localhost:3007/sellers-toolkit/";
var spe_char_last =url.substr(url.length - 1);
if(spe_char_last == '/')
{
url = url.slice(0, -1);
if (url) {
url = "http://localhost:3007/sellers-toolkit";
window.location.href = url;
}
}

UPDATED: redirect url pass parameter from another page

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||'

javascript - redirecting

I can get the code to pop-up both alert but redirecting is not working. After adding an item it should redirect.
<script type="text/javascript" src="/_layouts/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
fields = init_fields();
// Where to go when cancel is clicked
goToWhenCanceled = '/test/English/YouCanceled.aspx';
// Edit the redirect on the cancel-button's
$('.ms-ButtonHeightWidth[id$="GoBack"]').each(function(){
$(this).click(function(){
STSNavigate(goToWhenCanceled);
})
});
// Edit the form-action attribute to add the source=yourCustomRedirectPage
function setOnSubmitRedir(redirURL){
var action = $("#aspnetForm").attr('action');
var end = action.indexOf('&');
if(action.indexOf('&')<0){
newAction = action + "?Source=" + redirURL;
}else{
newAction = action.substring(0,end) + "&Source=" + redirURL;
}
$("#aspnetForm").attr('action',newAction);
alert(redirURL);
}
/*
// Use this for adding a "static" redirect when the user submits the form
$(document).ready(function(){
var goToWhenSubmitted = '/test/English/ThankYou.aspx';
setOnSubmitRedir(goToWhenSubmitted);
});
*/
// Use this function to add a dynamic URL for the OnSubmit-redirect. This function is automatically executed before save item.
function PreSaveAction(){
// Pass a dynamic redirect URL to the function by setting it here,
// for example based on certain selections made in the form fields like this:
var dynamicRedirect = '/surveys/Pages/ThankYou.aspx';
// Call the function and set the redirect URL in the form-action attribute
setOnSubmitRedir(dynamicRedirect);
alert(dynamicRedirect);
// This function must return true for the save item to happen
return true;
}
function init_fields(){
var res = {};
$("td.ms-formbody").each(function(){
if($(this).html().indexOf('FieldInternalName="')<0) return;
var start = $(this).html().indexOf('FieldInternalName="')+19;
var stopp = $(this).html().indexOf('FieldType="')-7;
var nm = $(this).html().substring(start,stopp);
res[nm] = this.parentNode;
});
return res;
}
</script>
If you set window.location.href = 'SomeUrl' at any point, it should redirect right then. Looking at your code, I dont see that anywhere.
At what point are you trying to redirect?

Categories

Resources