Window.Open Java Script Variable - javascript

I am trying to pass a javascript variable to a new window that opens, however if i add a name of "_self", the variable will not be passed:
This won't work, appointmentId is undefined:
var w = window.open("../calendar/appointment.html","_self");
w.appointmentId = appt.id;
This does work:
var w = window.open("../calendar/appointment.html");
w.appointmentId = appt.id;
How can I pass a variable using the _self name, so a new tab/window is not opened?
The variables I am passing are huge. They would take up the URL limit. Sorry I didn't specify this earlier.
Thanks

An alternative is to pass the variable in the querystring.
To redirect:
window.location = "../calendar/appointment.html?appt_id=" + appt.id
On page load:
<script type="text/javascript">
// http://stackoverflow.com/a/901144/1253312
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
var results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
window.appointmentId = getParameterByName('appt_id');
</script>

An alternate way to do this is via window.location. For example:
window.location = "../calendar/appointment.html"; // this will send the user here in the current window
In addition, variables are typically passed from page-to-page via the use of a QueryString (sometimes known as GET variables). These typically appear after a question mark. In your case, you could pass the variable like this:
window.location = "../calendar/appointment.html?appointmentId=" + appt.id;
// ../calendar/appointment.html?appointmentId=113
You could also pass the variable after a hash mark:
window.location = "../calendar/appointment.html#" + appt.id;
// ../calendar/appointment.html#113
If you go with the second option, then you can read the variable via location.hash. If you pass it via the QueryString, then you can extract the variable back out of the URL as shown in this question:
How can I get query string values in JavaScript?

window.open can take 3 parameters
https://developer.mozilla.org/en-US/docs/Web/API/Window.open
The second parameter you are passing is the name of the created window.
This is why you don't have it inside the window.
window.open(strUrl, strWindowName[, strWindowFeatures])
Information about supported features can be found in the given url.

The reason why the code you posted doesn't work is because when you use _self, the old document gets cleaned up before the new document can be loaded. Thus, there is no moment in time when the two can communicate synchroneously.
This answer for a slightly different question, but with the same root cause gives several asynchronous communication approaches:
Options you can use are :
Adding it as a parameter using the hash tag (second.php#tmpstr=aaaaaa
Using cookies (there is a nice jQuery cookie plugin)
Moving your whole page into a iFrame (not recommended) and redirecting only the main frame.
Note that using the hash tag is slightly better than using the query string suggested by the other answers because your variable will not end up on the request to the server.

You can use the browser's session storage.
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
Before redirecting:
sessionStorage.setItem("appointmentId", appt.id);
Redirect:
window.location = "../calendar/appointment.html";
When appointment.html loads:
window.appointmentId = sessionStorage.getItem("appointmentId");

Related

Get URL parameters with Javascript

Hi I have the following tag inside my HTML:
<script type="text/javascript" src="http://XX/teste1.php?BLABLABLA"></script>
Is there somewhay inside teste1.php, using JS to retrieve the parameters BLABLABLA? If I use window.location.href I get the index.php location (of course) but I need to get the parameters sent to the external resource using JS and not PHP.
I think I understood what you are after. Take a look the following fiddle.
http://jsfiddle.net/gK58u/2/
You can see I'm manually loading in jQuery, and then getting the src from the script declaration.
===================
HTML Add an id to your script declaration
<script id="jquerysrc" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js?key=test"></script>
Javascript
$(document).ready(function() {
var scriptsource = "";
scriptsource = $("#jquerysrc").attr("src");
alert(scriptsource);
});
This will allow you see the url that your external js file is coming from. This is more a point in the right direction.
You can try this, without using jQuery.
var scripts = document.getElementsByTagName('script'),i,src;
for(i=0;i<scripts.length;i++){
src = scripts[i].src;
if (src && src.indexOf('?')>=0){
console.log(src.substring(src.indexOf('?')+1));
}
}
Currently JavaScript don't have any of the built-in function for such purpose. What you're talking about i.e. BLABLABLA is known as Query String. Which is attacked to the URL to make a dynamic web page (change the content depending on the condition)
First Method
Is to get the whole URL, and then replacing the URL with empty string and so on to get only the last element.
Second method
Another answer was posted with a function (custom function, not a builtIn function). In which you pass on a parameter to the method, which gets the parameter values for you. It is easy to understand too.
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
To call the function, you use getParameterByName('prodId'). Use it inside a function or variable and you're good to go.
It seem you don't understand how PHP and JS works together.
Php generate HTML (maybe JS and CSS too). Then when this html is loaded by a client, JS is executed.
To get it in PHP or JS, you can use regex or modify the url from ?BLABLABLA to ?key=BLABLABLA. In PHP, "BLABLABLA" will be stored in $_GET['key']
EDIT :
well I misunderstood your question.
From "How to retrieve GET parameters from javascript?" :
-------------------------
With the window.location object. This code gives you GET without the question mark.
window.location.search.replace( "?", "" );
-------------------------
From your example it will return BLABLABLA
window.location DOC
EDIT2 :
When you generate your Javascript in teste.php, you should do this :
$str = "";
foreach ($_GET as $key => $value) {
$str = $key;
}
echo "var getParam = ".$str.";";
I don't see how to avoid foreach if you don't know what is given. You may have to rebuilt the parameters string ("?xxx=sss&ddd=zz...")
Now you JS variable getParam should contains BLABLABLA
Apolo

How to remove some part of the URL in the address bar of the browser

I try to remove a part of my url in the addressbar of the browser via javascript.
but I don't understand why it's not working, if I test it in the console the result is correct but it still does not change in the address bar.
How can I do it?
url I have:http://localhost:8090/Home/Index?x=72482&success=itsdone
url I want is:
http://localhost:8888/Home/Index?x=72482
here is my javascript code:
window.location.href.replace('&', '#');
window.location.hash = "";
replace doesn't change the string on which you call it (strings are immutable), it returns a new one.
To replace & with #, do
window.location = window.location.href.replace('&', '#');
If you want to remove everything from the first &, the best is to use a regular expression :
window.location = window.location.replace(/&.*$/,'');
If what you want is to retain the x parameter, then you should rebuild the location to ensure it's still OK if the parameters are in a different order in the URL :
window.location = window.location.replace(/([^?]*).*(\?|&)(x=)([^&]+).*/, "$1?$3$4")
This changes
"http://localhost:8888/Home/Index?a=2&x=72482&c=3"
or
"http://localhost:8888/Home/Index?x=72482&success=itsdone"
into
"http://localhost:8888/Home/Index?x=72482"
window.location will cause a page reload. to change the port too use this
window.location = window.location.protocol
+ "//"
+ window.location.host
+ ":8888/"
+ window.location.pathname
+ window.location.search.substr(0, window.location.search.indexOf('&')-1)
Is there a particular reason why you are passing isDone as a QueryString parameter if you do not even need it? Wouldn't it be easier to not even pass it to begin with and have the page decide if you are done?

Change the pathname in the URL of a link while keeping the querystring constant

From a page with the following URL, http://example.com/foo.html?query=1&other=2, I want to create a link to http://example.com/bar.html?query=1&other=2. How do I do that without explicitly saving and reloading all the query strings.
I need this to easily link from an iframe version of a page (embed.html?query) to the full page (index.html?query).
I would have recommended using the Location object's search method (available at document.location or window.location) to pull out the parameters, then modify the rest of the URL, but that API is apparently specific to Firefox.
I would simplify #DMortensen's answer by just splitting on the first ?, then modifying the first part (which will be the URL's path portion only), and reapplying the second part.
If you need to parse the parameters, I recommend the jQuery plugin Query Parameter Parser: one call to $.parseQuery(s) will pull out an object of all the keys & values.
It can be finicky, but you could split the URI on '?' and then loop through the 2nd element of that array to grab the key/val pairs if you need to evaluate each pair (using '&' as a delimiter). The obvious weakness in this would be if there are additional '?' or '&' used in the URI.
Something like this maybe? (pseudocode-ish)
var URI = document.URL;
var qs = URI.split('?');
var keyvalpair = qs[1].split('&');
var reconstructedURI = '&' + keyvalpair;
for(var i = 0; i< keyvalpair.length; i++){
var key = keyvalpair[i].split('=')[0];
var val = keyvalpair[i].split('=')[1];
}
Thank you for all the answers. I tried the following and it works.
function gotoFullSite() {
var search = window.location.search;
window.open("http://example.com/"+search)
}
$('#clickable').click(gotoFullSite);
and then use <a id = "clickable" href="#"></a>. When I click the link, it opens the proper website with all the query parameters in a new tab. (I need a new tab to break out of an iframe.)

How to Execute Javascript Code Using Variable in URL

I'm really new to Javascript and I'm having some trouble understanding how to get the following to work. My goal is to have a certain Javascript action execute when a page loads and a variable added to the end of the URL would trigger which Javascript action to execute. The URL of the page that I'm looking to implement this on is http://www.morgantoolandsupply.com/catalog.php. Each of the "+expand" buttons, which are Javascript driven, drop-down a certain area of the page. Ultimately, I would like to be able to create a URL that would automatically drop-down a certain category when the page loads. Could anybody explain to me the process to do this? Thanks in advance for any help!
You have to parse the URL somewhat "manually" since the parameters in the url aren't automatically passed to javascript, like they are in server-side scripting (via $_GET in PHP, for instance)
One way is to the use the URL fragment identifier, i.e. the "#something" bit that can go at the end. This is probably the neatest way of doing it, since the fragment isn't sent to the server, so it won't be confused with any other parameters
// window.location.hash is the fragment i.e. "#foo" in "example.com/page?blah=blah#foo"
if( window.location.hash ) {
// do something with the value of window.location.hash. First, to get rid of the "#"
// at the beginning, do this;
var value = window.location.hash.replace(/^#/,'');
// then, if for example value is "1", you can call
toggle2('toggle' + value , 'displayText' + value);
}
The URL "http://www.morgantoolandsupply.com/catalog.php#1" would thus automatically expand the "toggle1" element.
Alternatively, you can use a normal GET parameter (i.e. "?foo=bar")
var parameter = window.location.search.match(/\bexpand=([^&]+)/i);
if( parameter && parameter[1]) {
// do something with parameter[1], which is the value of the "expand" parameter
// I.e. if parameter[1] is "1", you could call
toggle2('toggle' + parameter[1] , 'displayText' + parameter[1]);
}
window.location.search contains the parameters, i.e. everything from the question mark to the end or to the URL fragment. If given the URL "example.com/page.php?expand=foo", the parameter[1] would equal "foo". So the URL "http://www.morgantoolandsupply.com/catalog.php?expand=1" would expand the "toggle1" element.
I'd perhaps go for something more descriptive than just a number in the URL, like, say use the title of the dropdown instead (so "#abrasives" or "expand=abrasives" instead of "#1" or "expand=1"), but that would require a little tweaking of your existing page, so leave that for later
You've already got the function to call: toggle2(), which takes two parameters that happen to be identical for all categories except for a number at the end. So create a URL that includes that number: http://www.morgantoolandsupply.com/catalog.php#cat=4
Then find that number in location.hash using a regular expression. This one is robust enough to handle multiple url parameters, should you decide to use them in the future: /[\#&]cat=(\d+)/. But, if you expect to never add anything else to the url, you could use a very simple one like /(\d+)/.
Once you've got the number, it's a simple matter of using that number to create your two parameters and calling toggle2().
This should work:
window.onload = function() {
if (/[\#&]cat=(\d+)/.test(location.hash)) {
var cat = parseInt(RegExp.$1);
if (cat > 0 && cat < 13) {
toggle2("toggle"+cat, "displayText"+cat);
}
}
}
Not a complete answer ("Give a man a fish" and all that), but you can start with something along these lines:
// entire URL
var fullURL = window.location.href;
// search string (from "?" onwards in, e.g., "www.test.com?something=123")
var queryString = window.location.search;
if (queryString.indexOf("someParameter") != -1) {
// do something
}
More info on window.location is available from the Mozilla Developer Network.
Having said that, given that you're talking about a PHP page why don't you use some server-side PHP to achieve the same result?

How do I trim/strip the URL down to the page name?

How would I go about trimming/stripping the URL down to the page name...
So: http://www.BurtReynoldsMustache.com/whatever/whoever/apage.html
Would become: apage.html
Any ideas?
you do not need jquery:
var url = window.location.href;
var page = url.substring(url.lastIndexOf('/') + 1);
Edit: a good point of the possible query string:
// it might be from browser & / anywhere else
var url = window.location.href;
url = url.split('#').pop().split('?').pop();
var page = url.substring(url.lastIndexOf('/') + 1);
ok, if the location object is available, use pathname gives better result as show below, however, a url can be a string or something directly from text field or span/label. So above solution should have its place.
With location and any link (<a>) elements on the page, you get a load of properties that give you specific parts of the URL: protocol, host, port, pathname, search and hash.
You should always use these properties to extract parts of the URL in preference to hacking about with href and probably getting it wrong for corner cases. For example, every solution posted here so far will fail if a ?query or #fragment is present. The answers from Rob and digitalFresh attempt to cope with them, but will still fail if a / character is present in the query string or fragment (which is valid).
Instead, simply:
var pagename= location.pathname.split('/').pop();
Most of the solutions here are not taking advantage of the window.location object. The location object has this wonderful thing called pathname which returns just the path, no query string, host, protocol, hash, etc.
var mypage = window.location.pathname.split("/").pop();
You could do something like this:
document.location.href.split('/').pop();
Edit: you probably want to get rid of the query string if there is one also:
document.location.href.split('/').pop().split('?').shift();
Edit 2: this will also ignore an anchor in the url if there is one
document.location.href.split('/').pop().split(/\?|#/).shift();
This should also exclude query and hash values.
var path = location.href;
path = path.substring(path.lastIndexOf("/") + 1);
path = path.split("?")[0].split("#")[0];
console.debug(path);
Haven't tested so compeltely guessed, but I'm sure something like this will do :-)
var url = 'http://www.BurtReynoldsMustache.com/whatever/whoever/apage.html';
var page = url.split('/');
alert(page[page.length-1]);​
EDIT Tested under jsfiddle and it was wrong, the above code should now work :-)

Categories