GET parameters from URL - javascript

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

Related

Pass URL parameters through to next page with Javascript (or not)

I think this is simple but can't seem to find the answer.
In our autoresponder, when a contact clicks a link to visit a page, the contact id and email are passed through to the next page.
So by clicking an email, the contact lands on page.com/1/?id=123&email=name#gmail.com
On that page, and there is a button to click to go to the next page...
what do I need to do so the parameters pass to the next page and the contact lands on page.com/2/?id=123&email=name#gmail.com?
Thanks for the help!
If the page number is all that changes:
button.addEventListener('click', () => {
const currentPage = Number(window.location.href.match(/\d+/));
window.location.href = window.location.href.replace(/\d+/, currentPage + 1);
});
Edit: here is a function to get the querystring parameters
from This link
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, " "));
}
If you already know the base url, and have the parameters just combine the two and redirect.
document.getElementById("myButton").onclick = function () {
var url = "page.com/2"; //get your base url how ever you're doing it.
var queryString = "?id=123&email=name#gmail.com";
var fullUrl = url + queryString;
window.location.href = fullUrl ;
};

JavaScript function for retrieving multiple querystring values

This function works only for a parameter.
function getQueryStringValue(key) {
debugger;
return unescape(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + escape(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
};
Please I need a JavaScript function that can retrieve more than one querystring parameter, I need to pass the name of the parameter as key to the function. Thank you
The function in the link Alex shared is as below
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, " "));
};
With my url as this:
var url= 'search-results.html?param1=unth?param2=lagos';
And I pass this to the function :
var param1 = getParameterByName('param1');
var param2 = getParameterByName('param2');
It return param1 as : luth?param2=lagos
instead of luth.
This is the same issue with the function I shared.
My question is a JavaScript Function that retrieves multiple querystring parameter but the function works only for one parameter
Your URL should be:
var url= 'search-results.html?param1=unth&param2=lagos';
In this case function will work.
var param1 = getParameterByName('param1'); //return unth
var param2 = getParameterByName('param2'); //return lagos

Get ID from link on the page

I have two pages in my Moodle. The first is the enrolment page and the second is the course page. On each of them I have a button, which prints PDF. On the enrolment page there are breadcrumbs, which look like that:
Startpage->Course->Miscellaneous->Learning Course
1->Enrolment->Enrolment Options
Under Learning Course 1 there is a link, which is:
http://localhost/mymoodle/course/view.php?id=6
How to get the id from this link? I need the id in order to get the course information into PDF.
I build up the functionality to get the id on course level and the code works:
$('#page-enrol-index .printpdf').click(function() {
//jquery extend function
$.extend(
{
redirectPost: function(location, args)
{
var form = '';
$.each( args, function( key, value ) {
form += '<input type="hidden" name="'+key+'" value="'+value+'">';
});
$('<form action="'+location+'" method="POST">'+form+'</form>').appendTo('body').submit();
}
});
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
//create the pdf
$.redirectPost("http://localhost/mymoodle/local/getinfo/getinfocourse.php", {
id: vars['id']
});
When trying to get the id it from the enrolment url
http://localhost/mymoodle/enrol/index.php?id=6
It won't work.
The id is needed in order to get the information from the course for the pdf, where there is:
$courseid = required_param('id', PARAM_INT);
The enrolment page just loads and the PDF isn't being printed, so I guess the PDF doesn't get the id from the course? I am new to Moodle and Javascript, so any help will be appreciated.
You could use the Moodle single button function instead of Javascript.
$printpdfurl = new moodle_url('/local/getinfo/getinfocourse.php', array('id' => $id));
echo $OUTPUT->single_button($printpdfurl, get_string('printpdf', 'local_getinfo'));
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)", "i"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
// query string: 'http://localhost/mymoodle/course/view.php?id=6'
var id = getParameterByName('id'); // 6

getParameter - URL parameter with dynamic name values

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

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