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

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

Related

Appending UTM parameters to my current URL

I am grabbing the utm parameters from the URL on my index page, and storing them in local storage, then I am using the script below to grab the parameters from local storage and appending them to the end of the contact page's URL.
<script>
var parameters = localStorage.getItem("url");
const nextURL = window.location.href + parameters;
window.history.replaceState(nextURL);
</script>
Problem: This script works perfectly, except each time I refresh the contact page, it appends the parameters again. How can I fix this?
Use URL and URLSearchParams to parse and modify the URL for you. That way you don't have to do any work to produce a valid string:
function buildUrl(fromURL, fromQuery) {
const url = new URL(fromURL);
const query = new URLSearchParams(fromQuery);
for (const [key, value] of query) {
url.searchParams.set(key, value);
}
return url.toString()
}
function test(fromURL, fromQuery) {
const url = buildUrl(fromURL, fromQuery);
return `fromURL: ${fromURL}
fromQuery: ${fromQuery}
result: ${url}
---------------------`;
}
console.log(test("http://example.com", ""));
console.log(test("http://example.com", "foo=1"));
console.log(test("http://example.com", "foo=1&bar=2"));
console.log(test("http://example.com", "foo=1&bar=2&baz=3"));
console.log(test("http://example.com?hello=world", ""));
console.log(test("http://example.com?hello=world", "foo=1"));
console.log(test("http://example.com?hello=world", "foo=1&bar=2"));
console.log(test("http://example.com?hello=world", "foo=1&bar=2&baz=3"));
console.log(test("http://example.com?bar=someValue", ""));
console.log(test("http://example.com?bar=someValue", "foo=1"));
console.log(test("http://example.com?bar=someValue", "foo=1&bar=2"));
console.log(test("http://example.com?bar=someValue", "foo=1&bar=2&baz=3"));
You can always do a quick if statement to check if parameters exists in the current URL and if not, add it.
if(window.location.href.indexOf("?" + parameters) == -1){
const nextURL = window.location.href + '?' + parameters;
window.history.replaceState('', '', nextURL);
}

How to store text box value to be passed to getJson request as query parameter

I need to be able to store the text value of a search box term, which can be used as a query parameter in a getJson request. I'm appending the search term to the end of the url the user is taken to after hitting the enter key, but the issue is that on the location replacement, it shows up as an error because the url for the page is /faq/search-results/.
$(".faq-search").keyup(function(e){
if(e.which == 13) {
window.location.replace("/faq/search-results/" + $(".faq-search").text());
}
});
Once the user has been sent to the search results page, I have a script which, if the user is on that url, is supposed to grab the search term from the pathname in the url, and submit it as a query parameter to the getJson request:
if(window.location.pathname == "/faq/search-results/"){
$("document").ready(function(e) {
var url = window.location.pathname;
var exp = url.split(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/);
var question = exp[5].split("/")[3];
$.getJSON("//search.url-to-search.com?q=" + question + "&results_type=faq", {
},
//Get results and make 'em look good
function(data) {
console.log(data);
$.each(data.data, function(i, data) {
if(data.type === "FAQ"){
$(".faq-results").append("<li class='result-item'><h3>" + data.title + "</h3><p class=\"content\">" + data.text + "</p><p class=\"category\">" + data.type + "</p></li>");
}
});
});
});
}
I believe the issue is that it won't fire off the request because its looking for only /faq/search-results/. I think I need a way to store the search term as a variable and pass it as a query parameter, but not sure how to accomplish this, as I believe it would make the variable out of scope.
A couple of things are wrong in your code:
first to collect the input value use .val() note text().
Secondly you are not passing the input value as a query string you are adding it to the url path /helloWorld. I think it is better to add as a query string ?q=helloworld.
I have therefore adjusted your code, removed your code to extract the text from the path and implemented a function to extract a named query param, this function is called getParameterByName.
The code below should be pretty much self explanatory.
$("document").ready(function(e) {
//
// Collects the input param as passes it as a query string note
// ?q= our string
//
$(".faq-search").keyup(function(e) {
if (e.which == 13) {
window.location.assign("file:///C:/Users/spydre/Desktop/text.html?q=" + $(".faq-search").val());
}
});
// snippet gets a query param from url
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, " "));
}
// collect any query string param whos name is q
var question = getParameterByName("q");
if (question) {
// pass question to our getJson
$.getJSON("//search.url-to-search.com?q=" + question + "&results_type=faq", {},
//Get results and make 'em look good
function(data) {
console.log(data);
$.each(data.data, function(i, data) {
if (data.type === "FAQ") {
$(".faq-results").append("<li class='result-item'><h3>" + data.title + "</h3><p class=\"content\">" + data.text + "</p><p class=\"category\">" + data.type + "</p></li>");
}
});
});
} //if question
})

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

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

Categories

Resources