This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 7 years ago.
I have been struggling with dynamically changing HTML content using URL variables. Let me give you an example and than provide you my code thus far.
Ex. I have a landing page with content to be changed. I would like to have a variable in my URL www.domain.com/header=new-content
I would like to be able to rewrite the HTML to show the new header using Javascript or Jquery. Here is what I have thus far. Seems like I am missing the trigger or if/else statement.
Thank you so much!
<script>
var element = document.getElementById("header");
element.innerHTML = "New Content";
</script>
First of all, when you're dealing with URL parameters, you should place a ? before you start defining parameters. This will result in the browser retrieving the page www.foo.bar/ instead of www.foo.bar/header=new-content. Once you add the question mark, you can retrieve URL parameters using the following snippet. I retrieved this from this question.
function getUrlParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
In your specific case, your final code, after defining the above function, might look something like this:
<script>
var header = getUrlParameter('header');
document.getElementById('header').innerHTML = header;
</script>
This will retrieve the URL parameter header and change the value of the element with ID header to the value contained in the URL. For the URL www.foo.bar/?header=new-content, the element's value would be changed to new-content. If you want to have spaces in the variable, you can remove the URL-encoded characters (ex. %20 for space) by changing the first line in the above snippet to this:
var header = decodeURIComponent(getUrlParameter('header'));
Last minute addition: I just noticed that another answer with more-or-less the same code snippet came in while I was writing this. Whoops. :)
You could read the url and extract the desired paramenter with a function such as:
function fGetUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
return sParameterName[1];
}
}
};
So if you are accessing a url such as:
http://www.domain.com/?header=new-content
You could store the parameter in a variable
var stringHeader = fGetUrlParameter("header")
and modify your element html
var element = document.getElementById("header");
element.innerHTML = stringHeader;
I'm not sure I understood your question.
Assuming that you want to pass a parameter using the URL the correct way to rewrite your url would be
www.domain.com?header=new-content
That would make your variable named header equal the value of new-content.
The way to extract your data would be:
<script>
var element = document.getElementById("header");
//use your variable
</script>
Related
In Shopify, i'm trying to get the ID of the selected variant in a script file. I was able to get the Variant ID by getting the URL parameter, but it is giving me the url parameter that was there prior to the on change event.
I tried doing an AJAX call, looped through the product variant IDs but no luck.
// Getting the URL Parameter for Variant ID
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
};
$('#option-color').change(function() {
var currentUrl = getUrlParameter('variant');
var variants = [];
var selected = $(this).val(),
mainImage = jQuery('.main-image img').attr('srcset'),
maxCount = 0;
$('.thumbnail').addClass('thumbnail--hidden');
$('.thumbnail--last').addClass('thumbnail--last');
arr = [];
var addImage = $.each(images, function(i, image) {
var alt = images[i].alt,
url = images[i].url;
if (( alt == selected || url == mainImage) && maxCount < 4) {
$($('.thumbnail img[alt="' + alt + '"]')[maxCount]).parents('.thumbnail').removeClass('thumbnail--hidden');
maxCount++
}
});
I basically want to be able to output the variant ID that it becomes after selecting on a new color.
When looking to get the variant ID of the currently selected variant, you should setup a listener on the actual element that changes the variant. All those active elements emit a type of "change" event you can listen to. When you get the change event, typically you get a variant to inspect, but if not, you can always query the element for its current value.
Looking in the URL is probably the least efficient and least trustworthy way to do this. Not all themes bother placing the current variant in the URL, and like you have pointed out, depending on when you choose to examine and parse that value, it might not represent what you want.
So the safest approach is examine the DOM and figure out the element the customer selected variants with, and dig through that to discover the "change" and subsequent value.
Im trying to get a stored variable that came in a url to be used as a variable with href.
The code I have so far is:
function GetUrlValue(VarSearch){
var SearchString = window.location.search.substring(1);
var VariableArray = SearchString.split('&');
for(var i = 0; i < VariableArray.length; i++){
var KeyValuePair = VariableArray[i].split('=');
if(KeyValuePair[0] == VarSearch){
return KeyValuePair[1];
}
}
}
And this works
http://www.somesite.com/?title=1254&keyphrase=phase1
arrives to the page with the script and it does store the values for title and keyphrase.
What Im trying to do is to build a href that in the end has a link like this:
http://www.anewsite.com/1254/
The domain will never change - only the variable at the end.
Is this possible ?
Any help will be most appreciated.
I have a HTML page which is loaded using a URL that looks a little like this:
http://localhost:8080/GisProject/MainService?s=C&o=1
I would like to obtain the query string parameters in the URL without using a jsp.
Questions
Can this be done using Javascript or jQuery?
Because I want to test my page using my Node.js local server before deploying it in the remote machine which uses a Java server.
Is there any library that will allow me to do that?
A nice solution is given here:
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
And this is how you can use this function assuming the URL is,
http://dummy.com/?technology=jquery&blog=jquerybyexample:
var tech = GetURLParameter('technology');
var blog = GetURLParameter('blog');`
Chrome 49 implements URLSearchParams from the URL spec, an API which is useful for fiddling around with URL query parameters. The URLSearchParams interface defines utility methods to work with the query string of a URL.
So what can you do with it? Given a URL string, you can easily extract parameter values as in the code below for s & o parameter:
//http://localhost:8080/GisProject/MainService?s=C&o=1
const params = new URLSearchParams(document.location.search);
const s = params.get("s");
const o = params.get("o");
console.info(s); //show C
console.info(o); //show 1
Assuming that our URL is https://example.com/?product=shirt&color=blue&newuser&size=m, we can grab the query string using window.location.search:
const queryString = window.location.search;
console.log(queryString);
// ?product=shirt&color=blue&newuser&size=m
We can then parse the query string’s parameters using URLSearchParams:
const urlParams = new URLSearchParams(queryString);
Then we call any of its methods on the result.
For example, URLSearchParams.get() will return the first value associated with the given search parameter:
const product = urlParams.get('product')
console.log(product);
// shirt
const color = urlParams.get('color')
console.log(color);
// blue
const newUser = urlParams.get('newuser')
console log(newUser);
// empty string
Other Useful Methods
Let's get a non-encoded URL for example:
https://stackoverflow.com/users/3233722/pyk?myfirstname=sergio&mylastname=pyk
Packing the job in a single JS line...
urlp=[];s=location.toString().split('?');s=s[1].split('&');for(i=0;i<s.length;i++){u=s[i].split('=');urlp[u[0]]=u[1];}
And just use it anywhere in your page :-)
alert(urlp['mylastname']) //pyk
Even works on old browsers like ie6
I am having a flash application where I want to send paramters to it via the javascript from a defaul.aspx page.
I have a paramter called Id where it can accept alphanumerica values.
the query string in the url works fine if I enter just numbers for the Id, and takes me to the specific page relted to that id , but if I enter a combination of numbers and characters like 001A , it does not work.
this is the code I used
<script type="text/javascript">
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0; i<vars.length; i++)
{
var pair = vars[i].split("=");
if (pair[0] == variable)
return (pair[1]);
}
}
</script>
and then later I assigned the first page of flash application to it.
flashvars.StartPage = getQueryVariable("Id");
and then passed the flashvars into swfobject.embedSWF
I also don't want to change anything in my mxml files in flash side
I appreciate if anyone could help me what the problem is
thanks
No you don't need to use JavaScript to process the value from querystring and then to send to flash.
Just make use of ExternalInterface.call function to grab variables (In this case : GET ) from URL.
Here's the code how it works. Add this code inside your MXML.
var pageURL : String = ExternalInterface.call("window.location.href.toString");
var paramPairs : Array = pageURL.split("?")[1].split("&");
for each (var pair : String in paramPairs)
{
var pairHolderx:Array = pair.split("=");
arrVals[counter]=pairHolderx[1];
counter++;
}
So if your URL is like http://www.stackoverflow.com/page.aspx?id=230A78&id2=8934
The arrVals[0] contains 230A78 and arrVals[1] contains 8934
Anyone know the quickest way to grab the value of a CGI variable in the current URL using Prototype? So if I get redirected to a page with the following URL:
http://mysite.com/content?x=foobar
I am interested in retrieving the value of "x" (should be "foobar") in a function called on page load like this:
Event.observe(window, "load", my_fxn ());
Thanks
You may want to look at the parseQuery method. This should do all the splitting you'd expect on a standard querystring such as document.location.search
http://api.prototypejs.org/language/string.html#parsequery-instance_method
For example:
document.location.search.parseQuery()["x"];
Will be undefined if it's not present, and should be the value otherwise.
I couldn't find any shortcuts here, so in the end I just parsed the URL with js like so:
function my_fxn () {
var varsFromUrl = document.location.search;
// get rid of first char '?'
varsFromUrl = varsFromUrl.substring(1);
var pairsArray = varsFromUrl.split("&");
for (i = 0; i < pairsArray.length; i++) {
var pair = pairsArray[i].split("=");
if (pair[0] == "x")
alert(pair[1] + ' is what I want.');
}
}