getParameter - URL parameter with dynamic name values - javascript

I've been strugling looking for a way to set a cookie if a URL parameter is persent. The problem is, the name of the URL parameter is half dynamic.
The URL would be:
http://zzzz.test.bbbb/index.html?transaction[XXXX][zzzzz]=YYYYY
Where XXXX and zzzzz are part o the URL name but can change according to what's in the link.
How would the correct getParameterByName function look like in order to recognize the URL parameter transaction[XXXX][zzzzz] ?
I've tried this but it does not work:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp(name + '(?:\\[\\d+\\]?:\\[\\d+\\])?=' + '(.+?)(&|$)'),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
if (getParameterByName("transaction")) {
set_cookie ("Transaction_ID", getParameterByName("transaction"));
}
Any ideas?

Check this JSBIN. This will help you.
Replace locatStr by window.location.search; The below code will work in all scenarios
function getParameterByName(){
var locatStr = '?xyz=123&transaction[XXXX][zzzzz]=YYYYY',
searchStr = locatStr.split('?')[1],
matchArr = searchStr.match(/transaction\[[a-zA-Z0-9]+\]\[[a-zA-Z0-9]+\]/gi),
para;
if(matchArr){
var temp = searchStr.split(matchArr[0]+'=')[1];
return ((temp.indexOf('&')!=-1) ? temp.split('&')[0] : temp);
}
else{
return false;
}
}
var param = getParameterByName();
console.log(param);
if(param){
console.log('set cookie here');
}
else{
console.log('no cookie present');
}
P.S. Dont forget to accept the answer if satisfied

Related

Set body class based on url with params

Im trying to set a body class based on the url - I can get it to work with a plain /Tablet/ url, like the code below.
But I need to set it to a url that has params in it, and I can't get that to work. How do I do it with this url?
/Tablets/?param=grid&pld0page=1&spcs=1
Script:
$(function() {
var loc = window.location.href; // returns the full URL
if(/Tablets/.test(loc)) {
$('body').addClass('test');
}
});
If, as you have mentioned in comments, the query parameter order is important, you can use this...
var url = location.pathname + location.search
console.info(url)
$(document.body).toggleClass('test',
url === '/Tablets/?param=grid&pld0page=1&spcs=1')
This lets you omit the URL scheme, host and port parts, focusing only on the path and query parameters.
You just have to search for text you want in the url string. You are doing fine in the code above. Just change
$(function() {
var loc = window.location.href; // returns the full URL
if(loc.includes('Tablets')) { // will return true/false
$('body').addClass('test');
}
});
Read on includes or here. You can do the same for other tests too, if you are checking for other strings in url. Hope this helps.
You can use this
$(function() {
var url = window.location.href;
url = url.replace(/^.*\/\/[^\/]+/, '')
if(url == '/Tablets?param=grid&pld0page=1&spcs=1') {
$('body').addClass('test');
}
});
If your URL is "http://www.google.com/?param=grid&pld0page=1&spcs=1", then the above queryString variable would be equal to "?param=grid&pld0page=1&spcs=1".
You can check the string is not empty
Replace your code with this
var loc = window.location.href; // returns the full URL
var url = loc.split( '/' );
var chunk = url[ url.length - 2 ];
if(loc.indexOf(chunk) >= 0) {
$('body').addClass('test');
}
var loc = 'http://localhost/Tablets/?param=grid&pld0page=1&spcs=35';
var patt = new RegExp("/Tablets/");
if(patt.test(loc) && loc.split('?').length > 1)
{
console.log('true');
$('body').addClass('test');
}
else
{
console.log('false');
$('body').removeClass('test');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

GET parameters from URL

I have an URL like http://www.test.pl/product-pol-4406.html
With Geasemonkey scripts I want to get the "4406" part from the URL, but I don`t have any idea how to do it. My code is:
var input=document.createElement("input");
input.type="button";
input.value="Edytuj";
input.alt="visitPage";
input.onclick = visitPage;
input.setAttribute("style", "font- size:18px;position:absolute;top:120px;right:40px;");
document.body.appendChild(input);
function visitPage(){
window.location='https://test.pl/panel/product-edit.php?idt=4406';
}
Any suggestions? Please.
use below function to get your 'idt' value in javascript
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var result= = getParameterByName('idt');
Just use
var url = window.location.href;
To get the full URL. According to your needs you could parse the URL with regex afterwards to get what you need, or e.g. split it to get parts of it with a seperator that makes sense with the type of URLs you are working with.
If you want to take the product id from the given url and then pass to the php page. You can try this
var url = "http://www.test.pl/product-pol-4406.html" //window.location.href
if(url){
url = url.substr(url.lastIndexOf("/") + 1);
var productID = url.match(/\d+/);
alert(productID);
}
Update:
function getProductID(){
var url = "http://www.test.pl/product-pol-4406.html" //window.location.href
if(url){
url = url.substr(url.lastIndexOf("/") + 1);
return url.match(/\d+/);
}
}
And then call the function inside the visitePage() function
function visitPage(){
var productID = getProductID();
if(productID){
window.location='https://test.pl/panel/product-edit.php?idt='+productID;
}
}

Show/hide div based on URL - works locally but not on live server

I'm using some jQuery to show/hide a div based on a URL parameter (?rp=):
$(function () {
if (document.location.href.indexOf('rp') > -1) {
$('#rphide').hide();
} else {
$('#rphide').show();
}
});
It works locally and on a development server, however on the live server the div is permanently hidden EVEN if there's no ?rp= in the querystring. I'm confused as to why this is happening? Thanks.
it is hard to find issue with such details but here is another approach to do the same.
you are trying to search string "rp" in url, which is not good in case if you have rp in domain name. so better approach would be find query in url.
Use this function to get param.
$(function () {
if (getQueryStringParamByName('rp') != "") {
$('#rphide').hide();
} else {
$('#rphide').show();
}
});
function getQueryStringParamByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

How to add a param to a URL that trigger jQuery to run a function on load

Is there a way to add a url param like: http://site.com?open=true
And on document ready, if jQuery sees the open param set to true execute a function?
Thanks
first lets make a good Query string searcher in JS
function querySt(qsName, url)
{
var theUrl;
if (url == null || url == undefined)
theUrl = window.location.search.substring(1); else theUrl = url;
var g = theUrl.split("&");
for (var i = 0; i < g.length; i++) {
var pair = g[i].split("=");
if (pair[0].toLowerCase() == qsName.toLowerCase())
{
return pair[1];
}
}
return null;
}
$(function (){
if (querySt("open")!='true') return;
});
taken from website http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/
function $_GET(q,s) {
s = s ? s : window.location.search;
var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i');
return (s=s.replace(/^?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
}
You can test location.href with a regex:
if (location.href.match(/open=true/)
// do something
You might want to work on the regex though, to make sure it works for you.

jQuery redirect to source url

I would like to redirect a user to a target URL on a button click. The target URL is variable and has to be read from the current page URL parameter 'source':
For instance, I have a url http://w/_l/R/C.aspx?source=http://www.google.com
When the user clicks on a button he's being redirect to http://www.google.com
How would I do that with jQuery?
first of all you need to get the url param : source
this can be done with a function like :
function GetParam(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
// you can use it like
var source = GetParam('source');
//then
window.location.href = source
On button click handler, just write window.location.href = http://www.google.com
You will need to parse the query string to get the value of the variable source.
You don't need jQuery for it.
A simple function like this will suffice:
function getFromQueryString(ji) {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i = 0; i < gy.length; i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
location.href = getFromQueryString("source");
Using the url parsing code from here use this to parse your url (this should be included once in your document):
var urlParams = {};
(function () {
var e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q))
urlParams[d(e[1])] = d(e[2]);
})();
Then do this to redirect to the source parameter:
window.location.href = urlParams["source"];
Since you are using the jQuery framework, I'd make use of the jQuery URL Parser plugin, which safely parses and decodes URL parameters, fragment...
You can use it like this:
var source = $.url().param('source');
window.location.href = source;
get url params : (copied from another stackoverflow question) :
var params= {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
params[decode(arguments[1])] = decode(arguments[2]);
});
window.location = params['source'];
You can do like this,
<a id="linkId" href=" http://w/_l/R/C.aspx?source=http://www.google.com">Click me</a>
$('#linkId').click(function(e){
var href=$(this).attr('href');
var url=href.substr(href.indexof('?'))
window.location =url;
return false;
});

Categories

Resources