how can I append variables to an URL with javascript without navigating to the url ?
thanks
To append variables to the hash (as Matthew suggested), you can do the following in plain JavaScript:
window.location.hash = 'varA=some_value;varB=some_value';
This will add #varA=some_value;varB=some_value to your URL. It will not refresh the page unless the hash value is equal to an anchor name or an element id within the document.
Then to check if a hash value is present, simply do the following:
var i, variables = window.location.hash.split(';');
if (variables.length > 0) {
// Variables present in hash
for (i = 0; i < variables.length; i++) {
keyValuePair = variables.split('=');
// keyValuePair[0] would be the key (variable name)
// keyValuePair[1] would be the value
}
}
else {
// No variables in the hash
}
You may also want to check out the following Stack Overflow post on issues related to the URL encoding of the hash part in different browsers:
Encoding of window.location.hash
You can modify window.location.hash. Anything else will cause a navigation.
I am not sure about that, but how is it with this?:
document.url + myVar + 'myString';
Though Javascript is not my language :P
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How can i select the fragment after the '#' symbol in my URL using PHP?
The result that i want is "photo45".
This is an example URL:
http://example.com/site/gallery/1#photo45
If you want to get the value after the hash mark or anchor as shown in a user's browser: This isn't possible with "standard" HTTP as this value is never sent to the server (hence it won't be available in $_SERVER["REQUEST_URI"] or similar predefined variables). You would need some sort of JavaScript magic on the client side, e.g. to include this value as a POST parameter.
If it's only about parsing a known URL from whatever source, the answer by mck89 is perfectly fine though.
That part is called "fragment" and you can get it in this way:
$url=parse_url("http://example.com/site/gallery/1#photo45 ");
echo $url["fragment"]; //This variable contains the fragment
A) already have url with #hash in PHP? Easy! Just parse it out !
if( strpos( $url, "#" ) === false ) echo "NO HASH !";
else echo "HASH IS: #".explode( "#", $url )[1]; // arrays are indexed from 0
Or in "old" PHP you must pre-store the exploded to access the array:
$exploded_url = explode( "#", $url ); $exploded_url[1];
B) You want to get a #hash by sending a form to PHP? => Use some JavaScript MAGIC! (To pre-process the form)
var forms = document.getElementsByTagName('form'); //get all forms on the site
for (var i = 0; i < forms.length; i++) { //to each form...
forms[i].addEventListener( // add a "listener"
'submit', // for an on-submit "event"
function () { //add a submit pre-processing function:
var input_name = "fragment"; // name form will use to send the fragment
// Try search whether we already done this or not
// in current form, find every <input ... name="fragment" ...>
var hiddens = form.querySelectorAll('[name="' + input_name + '"]');
if (hiddens.length < 1) { // if not there yet
//create an extra input element
var hidden = document.createElement("input");
//set it to hidden so it doesn't break view
hidden.setAttribute('type', 'hidden');
//set a name to get by it in PHP
hidden.setAttribute('name', input_name);
this.appendChild(hidden); //append it to the current form
} else {
var hidden = hiddens[0]; // use an existing one if already there
}
//set a value of #HASH - EVERY TIME, so we get the MOST RECENT #hash :)
hidden.setAttribute('value', window.location.hash);
}
);
}
Depending on your form's method attribute you get this hash in PHP by:
$_GET['fragment'] or $_POST['fragment']
Possible returns: 1. ""[empty string] (no hash) 2. whole hash INCLUDING the #[hash] sign (because we've used the window.location.hash in JavaScript which just works that way :) )
C) You want to get the #hash in PHP JUST from requested URL?
YOU CAN'T !
...(not while considering regular HTTP requests)...
...Hope this helped :)
I've been searching for a workaround for this for a bit - and the only thing I have found is to use URL rewrites to read the "anchor". I found in the apache docs here http://httpd.apache.org/docs/2.2/rewrite/advanced.html the following...
By default, redirecting to an HTML anchor doesn't work, because mod_rewrite escapes the # character, turning it into %23.
This, in turn, breaks the redirection.
Solution: Use the [NE] flag on the RewriteRule. NE stands for No
Escape.
Discussion: This technique will of course also work with other special
characters that mod_rewrite, by default, URL-encodes.
It may have other caveats and what not ... but I think that at least doing something with the # on the server is possible.
You can't get the text after the hash mark. It is not sent to the server in a request.
I found this trick if you insist want the value with PHP.
split the anchor (#) value and get it with JavaScript, then store as cookie, after that get the cookie value with PHP
If you are wanting to dynamically grab the hash from URL, this should work:
https://stackoverflow.com/a/57368072/2062851
<script>
var hash = window.location.hash, //get the hash from url
cleanhash = hash.replace("#", ""); //remove the #
//alert(cleanhash);
</script>
<?php
$hash = "<script>document.writeln(cleanhash);</script>";
echo $hash;
?>
You can do it by a combination of javascript and php:
<div id="cont"></div>
And by the other side;
<script>
var h = window.location.hash;
var h1 = (win.substr(1));//string with no #
var q1 = '<input type="text" id="hash" name="hash" value="'+h1+'">';
setInterval(function(){
if(win1!="")
{
document.querySelector('#cont').innerHTML = q1;
} else alert("Something went wrong")
},1000);
</script>
Then, on form submit you can retrieve the value via $_POST['hash'] (set the form)
You need to parse the url first, so it goes like this:
$url = "https://www.example.com/profile#picture";
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
If you need to parse the actual url of the current browser, you need to request to call the server.
$url = $_SERVER["REQUEST_URI"];
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
Getting the data after the hashmark in a query string is simple. Here is an example used for when a client accesses a glossary of terms from a book. It takes the name anchor delivered (#tesla), and delivers the client to that term and highlights the term and its description in blue so its easy to see.
setup your strings with a div id, so the name anchor goes where its supposed to and the JavaScript can change the text colors
<div id="tesla">Tesla</div>
<div id="tesla1">An energy company</div>
Use JavaScript to do the heavy work, on the server side, inserted in your PHP page, or wherever..
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
I am launching the Java function automatically when the page is loaded.
<script>
$( document ).ready(function() {
get the anchor (#tesla) from the URL received by the server
var myhash1 = $(location).attr('hash'); //myhash1 == #tesla
trim the hash sign off of it
myhash1 = myhash1.substr(1) //myhash1 == tesla
I need to highlight the term and the description so I create a new var
var myhash2 = '1';
myhash2 = myhash1.concat(myhash2); //myhash2 == tesla1
Now I can manipulate the text color for the term and description
var elem = document.getElementById(myhash1);
elem.style.color = 'blue';
elem = document.getElementById(myhash2);
elem.style.color = 'blue';
});
</script>
This works. client clicks link on client side (example.com#tesla) and goes right to the term. the term and the description are highlighted in blue by JavaScript for quick reading .. all other entries left in black..
I'm trying to get this conditional statement to work, but having no luck
<body onload="HashTagInsert()">
function HashTagInsert() {
var hash="window.location";
if (hash==="http://www.address.com#anchor1")
{
document.getElementById("insert-text").innerHTML="<h2>Title</h2><p>body text</p>";
}
else if (hash==="http://www.url.com/foler/code/page.html#anchor2")
{
document.getElementById("insert-text").innerHTML="<h2>Title</h2><p>body text</p>";
}
else ()
{
document.getElementById("insert-text").innerHTML="something else text"
}
}
</body>
If you want the hash variable to be the value of the window.location object, then don't put quotes around the object name as that will turn it into a string literal.
var hash = window.location;
I recommend not calling the variable hash though, as that could be confused with window.location.hash, which contains the fragment ID component of the URL.
Don't add quotes around window.location.
var hash = window.location.href;
If you want to compare your current window location with some string you need to set the "hash" variable correctly:
var hash = window.location;
but I am not sure if I got your problem.
In case that your javascript can not set your html properly, there is also a timing problem. It depends when your javascript gets called. Before or after your DOM has been rendered. Because if your javascript is executed before your DOM (and your element '#insert-text') is rendered, you wont be able to select this DOM element.
And ... but this is perhaps just my opinion, is is pretty uncool to have masses of if / else if / else constructions in your code.
You might want to map some url and text so that you do not need to make your life harder than it is.
for example:
var html;
var mapping = {
"http://www.address.com#anchor1":"<h2>Yeah</h2><p>Baby</p>",
"http://www.address.com#anchor2":"<h2>Cool</h2><p>Tomato</p>",
"default": "<h2>Woops</h2><p>Honolulu rocks</p>"
}
mapping[window.location.href] ? html = mapping[window.location.href] : html = mapping['default'];
document.getElementById("insert-text").innerHTML=html;
Our client has two URL's that point to the same page. Depending on which URL the user comes through they want to display and hide certain content. I have the following code and everything looks like it should work (doesn't it always....) but for some reason the if doesn't evaluate to true. The alert is in there for troubleshooting purposes.
var this_page = window.location;
var calc_address = "DIFFERENT ADDRESS";
alert(this_page);
if(this_page == "http://www.calculatesnowguards.com/"){
$('#mashead').css('background-image', 'url("../images/masthead_bg.jpg") ');
$('.calc_remove').hide();
$('#bottom').innerHTML = calc_address;
}
window.location is not a string, it's only represented as so. It's actually an object. window.location.href is the variable you want to compare to.
EDIT: (In response to the comments below.) With such different URLs, why would you try to compare them directly?
if (window.location.href.indexOf("calculatesnowguards.com") >= 0) {
//code for calculatesnowguards.com
} else{
//code for snowguards.biz
}
EDIT2: Sorry, didn't realize that contains() was a Firefox only function. I extend String to include it in my scripts.
I am customizing Denis Gritcyuk's Popup date picker.
This pop-up script uses inline Javascript in a href link, to set the selected date into the input field, in the parent window, that is was called for. An example URL looks like:
<a href="javascript:window.opener.document.formname.field.value='03-10-2011';
window.close();">3</a>
The input field name, (e.g. document.formname.field), is passed to the script as a string parameter.
I would like to add things done when that link is clicked (e.g. change background color of field, set flag, etc.). So while this DOES work, it's getting ugly fast.
<a href="javascript:window.opener.document.formname.field.value='03-10-2011';
window.opener.document.formname.field.style.backgroundColor='#FFB6C1';
window.close();">3</a>
How would I move these inline commands into a JS function? This would give me much cleaner URLs and code. The URL would now look something like
3
with a function like (this example obviously does NOT work):
function updateField (str_target, str_datetime) {
var fieldName = "window.opener" + str_target;
[fieldName].value = str_datetime;
[fieldName].style.backgroundColor = '#FFB6C1';
// Set flag, etc.
window.close();
}
So any suggestions on how this can be done, please?
I'd prefer to hide the dom path tracing back from the current window back to the opener. It's appropriate to bake that into the function since the function will always be used in the context of that child popup. Then your function call is cleaner and more readable. Obviously, replace "myField" with the ID of the field you're intending to update.
3
function updateField ( str_date, str_fieldname ) {
var fieldToUpdate = document.getElementById( str_fieldname );
fieldToUpdate.value = str_date;
fieldToUpdate.style.backgroundColor = '#FFB6C1';
// Set flag, etc.
window.close();
}
You're acessing the property incorrectly. Try:
function updateField (str_target, str_datetime) {
var fieldName = window.opener;
str_target = str_target.split('.');
for (var i = 0; i < str_target.length; i++)
fieldName = fieldName[str_target[i]];
fieldName.value = str_datetime;
fieldName.style.backgroundColor = '#FFB6C1';
// Set flag, etc.
window.close();
}
The bracket notation ([]) is only used for properties of objects, not objects themselves. If you found my post helpful, please vote for it.
You can build a string and evaluate it as code using the eval function, but I would recommend against it.
There are a couple of things wrong with your code:
You cannot use the [] operator in a global context, you have to suffix it on an object, so you can say window["opener"] and this will be equivalent to window.opener, but there is no such thing as simply ["window"]
When navigating nested properties, as in window.opener.document you cannot navigate multiple levels using the [] operator. I.e. window["opener.document"] is not allowed. You must use window["opener"]["document"] instead.
I have a video page that has filters for the videos. If I click on one of the filters (e.g. "music videos"), the url changes to something like this:
http://mysite.com/videos/?videofilter=music-videos
Unfortunately, there isn't a body class added or anything where I can easily target it by doing something like this:
body.music-videos { }
Is there a way to somehow target the url using CSS or JavaScript?
You could use Javascript's location.href to get the location, and work with it like a normal string.
But it would be much more recommended to server-side the body to have a class.
Presumably your page loads with that URL - can't you do somehting when you render the page to include something css-detectable?
I don't know if I understand your question. Are you trying to target a link with an href value? You should be able to target that with something like selector[src=URL] in css. If you're trying to target the body tag based on the URL I would create conditional scripts under if statements such as if(location.href=='url'){ document.getElementsByTagName("body").style.property="whatever" } . Hope this helps.
I'm not sure I understand...
So you click the filter options, which sends a query string to the URL. We can get the query string as such:
var qs = [];
var q = window.location.search.substring(1);
var p = q.split('&');
for(var i = 0; i < p.length; i++) {
var pos = p[i].indexOf('=');
if(pos > 0) {
var key = p[i].substring(0, pos);
var val = p[i].substring(pos+1);
qs[key] = val;
}
}
Then you simply access qs['videofilter']to get the value. From there, if it's doing nothing, well – you don't have a filter, you have check boxes. The only way to have a filter is to have some form of commonality by which to categorize them all. If you're wanting to do this through javascript and css, you could use that filter in a regex to find the specific tag whose innerHTML matches the value you got above, then determine the whole container's relationship( e.g. parent, grandparent, etc. ), and set that to display:none;
If you mean something else, please clarify.
This solution is Firefox only unfortunately:
From https://developer.mozilla.org/en/CSS/#-moz-document
#-moz-document url(http://www.w3.org/),
url-prefix(http://www.w3.org/Style/),
domain(mozilla.org)
{
/* CSS rules here apply to:
+ The page "http://www.w3.org/".
+ Any page whose URL begins with "http://www.w3.org/Style/"
+ Any page whose URL's host is "mozilla.org" or ends with
".mozilla.org"
*/
/* make the above-mentioned pages really ugly */
body { color: purple; background: yellow; }
}