Passing Javascript Variable to second html page and show [duplicate] - javascript

I have two pages - "page 1" and "page 2". On page 1 there's an text-box with a value of e.g. 100 and a button at the end.
By pressing the button I want javascript to save the value of the textbox in a global (?) variable and jump to page 2. With "window.onload" I want a second Javascript-function to alert the value saved at page1.
Here's my Javascript code:
<script type="text/javascript">
var price; //declare outside the function = global variable ?
function save_price(){
alert("started_1"); //just for information
price = document.getElementById('the_id_of_the_textbox').value;
alert(price); //just for information
}
<script type="text/javascript">
function read_price(){
alert("started_2");
alert(price);
}
On "page 1" I have this send-Button with:
<input class="button_send" id="button_send" type="submit" value="Submit_price" onclick="save_price();"/>
It starts the Javascript function and redirects me correctly to my page2.
But with this ont the second page:
window.onload=read_price();
I always get an "undefined" value of the global variable price.
I've read a lot about those global variables. E.g. at this page: Problem with global variable.. But I can't get it working...
Why is this not working?

Without reading your code but just your scenario, I would solve by using localStorage.
Here's an example, I'll use prompt() for short.
On page1:
window.onload = function() {
var getInput = prompt("Hey type something here: ");
localStorage.setItem("storageName",getInput);
}
On page2:
window.onload = alert(localStorage.getItem("storageName"));
You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.

Your best option here, is to use the Query String to 'send' the value.
how to get query string value using javascript
So page 1 redirects to page2.html?someValue=ABC
Page 2 can then
read the query string and specifically the key 'someValue'
If this is anything more than a learning exercise you may want to consider the security implications of this though.
Global variables wont help you here as once the page is re-loaded they are destroyed.

You have a few different options:
you can use a SPA router like SammyJS, or Angularjs and ui-router, so your pages are stateful.
use sessionStorage to store your state.
store the values on the URL hash.

To do this, I recommend sending data within the link data. This is a very simple way of doing it without PHP. Simply get the link in the second page and replace the previous link with "".
Page_One.html:
<script>
//Data to be transfered
var data = "HelloWorld";
//Redirect the user
location.replace("http://example.com/Page_Two.html?" + data);
</script>
Page_Two.html :
<script>
//Get the current link
var link = window.location.href;
//Replace all content before ? with ""
link = link.replace("http://example.com/Page_Two.html?","");
//Display content
document.write("Page_One.html contains:" + link + "");
</script>
Hope it helps!

I have a simple Approach rather (Pure JS):
Page One :
Goto Your Info
Note : You've to encode your GTK value (i.e parameter value) in Base64
Next is Page TWO :
<script>
// first we get current URL (web page address in browser)
var dloc= window.location.href;
//then we split into chunks array
var dsplt= dloc.split("?");
//then we again split into final chunk array, but only second element
//of the first array i.e dsplt[1]
var sanitize= dsplt[1].split("=");
// now here comes the tricky part, join all elements into single //string. IT may be the case, that base64 string contain '=' sign, we shall find it
var dlen= sanitize.length;
var FinString= "";
// we will start from 1, bcoz first element is GTK the key we don't // want it
for(i=1;i<dlen;i++)
{
FinString= FinString+sanitize[i];
}
// afterwards, all the Base64 value will be ONE value.
// now we will convert this to Normal Text
var cleantxt= window.atob(FinString);
document.getElementById("yourname").innerHTML= "Your Name is : <b>"+cleantxt+" .";
You can do anything with the parameter decoded info... Like Redirecting visitor
immediately to another page thru a "POST" method form automatically submitted
by Javasript to Lead a php page finally, without an visible parameters, but with
invisible hidden parms.

Related

C#/Razor replace second question mark with ampersand in query string

I am using C# and I have a CMS that uses an open text field. I am doing a redirect manually appending a query string BUT on top of that, I have editors putting UTMs into the URL. I am trying to track the redirects/vanity URLs so we an see the success of them, but the editors are adding UTMs and when I am transferring the redirect, I prepend "?ref=" to their URL to the second URL.
I need to know how to replace any subsequent question marks in the query string.
The CMS is seeing the second question mark and automatically redirecting to the homepage, because I think it is trying to be smart with the URL and the second question mark is causing it to think the URL is invalid.
So the original URL I am getting looks something like this:
www.mysite.com/somepage?utm_source=foo&utm_medium=bar
BUT it then redirects so I can track the URL and it looks now like this
www.myothersite.com/this-other-page?ref=www.mysite.com/somepage?utm_source=foo&utm_medium=bar
So what I want to do is in the second URL is to replace the second question mark with an ampersand. How would I do only the second or subsequent ones without getting rid of the first one?
I am using Javascript to do the redirect in the view.
My code so far
#{
var currentPageUrl = HttpContext.Current.Request.Url.AbsoluteUri;
}
<script type="text/javascript">
setTimeout(function () {
window.location.href = '#Model.Content.GetPropertyValue("externalRedirectURL")?ref=#currentPageUrl';
}, 200); //will call the function after 2 secs
</script>
I found my answer now using HTML.Raw and Json.Ecode.
When I did generic .Replace in the actual Javascript built string, for some reason the .Replace("?", "&") was adding another ampersand to anything in the query string with an ampersand already in the query string. Not what I expected.
Anyways, here is my answer
<script>
var currentP = #Html.Raw(Json.Encode(#currentPageUrl.Replace("?","&")));
setTimeout(function () {
window.location.href = '#Model.Content.GetPropertyValue("externalRedirectURL")' + '?ref=' + currentP;
}, 200); //will call the function after 2 secs
</script>

Get url of php file that execute phantomjs [duplicate]

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..

How to make a JS variable cross over HTML pages? [duplicate]

I have two pages - "page 1" and "page 2". On page 1 there's an text-box with a value of e.g. 100 and a button at the end.
By pressing the button I want javascript to save the value of the textbox in a global (?) variable and jump to page 2. With "window.onload" I want a second Javascript-function to alert the value saved at page1.
Here's my Javascript code:
<script type="text/javascript">
var price; //declare outside the function = global variable ?
function save_price(){
alert("started_1"); //just for information
price = document.getElementById('the_id_of_the_textbox').value;
alert(price); //just for information
}
<script type="text/javascript">
function read_price(){
alert("started_2");
alert(price);
}
On "page 1" I have this send-Button with:
<input class="button_send" id="button_send" type="submit" value="Submit_price" onclick="save_price();"/>
It starts the Javascript function and redirects me correctly to my page2.
But with this ont the second page:
window.onload=read_price();
I always get an "undefined" value of the global variable price.
I've read a lot about those global variables. E.g. at this page: Problem with global variable.. But I can't get it working...
Why is this not working?
Without reading your code but just your scenario, I would solve by using localStorage.
Here's an example, I'll use prompt() for short.
On page1:
window.onload = function() {
var getInput = prompt("Hey type something here: ");
localStorage.setItem("storageName",getInput);
}
On page2:
window.onload = alert(localStorage.getItem("storageName"));
You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.
Your best option here, is to use the Query String to 'send' the value.
how to get query string value using javascript
So page 1 redirects to page2.html?someValue=ABC
Page 2 can then
read the query string and specifically the key 'someValue'
If this is anything more than a learning exercise you may want to consider the security implications of this though.
Global variables wont help you here as once the page is re-loaded they are destroyed.
You have a few different options:
you can use a SPA router like SammyJS, or Angularjs and ui-router, so your pages are stateful.
use sessionStorage to store your state.
store the values on the URL hash.
To do this, I recommend sending data within the link data. This is a very simple way of doing it without PHP. Simply get the link in the second page and replace the previous link with "".
Page_One.html:
<script>
//Data to be transfered
var data = "HelloWorld";
//Redirect the user
location.replace("http://example.com/Page_Two.html?" + data);
</script>
Page_Two.html :
<script>
//Get the current link
var link = window.location.href;
//Replace all content before ? with ""
link = link.replace("http://example.com/Page_Two.html?","");
//Display content
document.write("Page_One.html contains:" + link + "");
</script>
Hope it helps!
I have a simple Approach rather (Pure JS):
Page One :
Goto Your Info
Note : You've to encode your GTK value (i.e parameter value) in Base64
Next is Page TWO :
<script>
// first we get current URL (web page address in browser)
var dloc= window.location.href;
//then we split into chunks array
var dsplt= dloc.split("?");
//then we again split into final chunk array, but only second element
//of the first array i.e dsplt[1]
var sanitize= dsplt[1].split("=");
// now here comes the tricky part, join all elements into single //string. IT may be the case, that base64 string contain '=' sign, we shall find it
var dlen= sanitize.length;
var FinString= "";
// we will start from 1, bcoz first element is GTK the key we don't // want it
for(i=1;i<dlen;i++)
{
FinString= FinString+sanitize[i];
}
// afterwards, all the Base64 value will be ONE value.
// now we will convert this to Normal Text
var cleantxt= window.atob(FinString);
document.getElementById("yourname").innerHTML= "Your Name is : <b>"+cleantxt+" .";
You can do anything with the parameter decoded info... Like Redirecting visitor
immediately to another page thru a "POST" method form automatically submitted
by Javasript to Lead a php page finally, without an visible parameters, but with
invisible hidden parms.

How would I save a JS variable so it can be used on another HTML page

I have two HTML pages. On the first page I add values to an array.
thisArray.push("new value");
On the second HTML page I want to print this array to a textArea
for(i=0; i<thisArray.length;i++){
var thisName = thisArray[i];
document.getElementById('listOfNames').innerHTML += thisName + '\n';
}
But when I change the page obviously the browser wont know about the other variable. What's the best way to do this ?
I thought of saving the value locally?
Is this the best way?
Use window.localStorage.
https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage
Example:
window.localStorage.myArray = JSON.stringify(arrayData)
And then parse JSON when read the data on another page.
You can use localStorage to persist the value,
localStorage.setItem('itemName', itemValue);
then to fetch the item just use
localStorage.getItem('itemName');
You can use localStorage.setItem(key,value)
Check out this library which allows you to set and read javascript cookies easily.
https://github.com/js-cookie/js-cookie
Example:
Set cookie on first page:
Cookies.set('thisArray', JSON.stringify(thisArray));
Read cookie on second page:
var thisArray = Cookies.getJSON('thisArray');
You have at least, two options to do what you want, one is pass that variable on the url query like:
www.mypage.com?my_javascript_var=12345
Another option is using localstorage
localStorage.setItem('itemName', varToBeSaved);
then, to get the variable back on any page
var mySavedVar = localStorage.getItem('itemName');

Passing Variable through JavaScript from one html page to another page

I have two pages - "page 1" and "page 2". On page 1 there's an text-box with a value of e.g. 100 and a button at the end.
By pressing the button I want javascript to save the value of the textbox in a global (?) variable and jump to page 2. With "window.onload" I want a second Javascript-function to alert the value saved at page1.
Here's my Javascript code:
<script type="text/javascript">
var price; //declare outside the function = global variable ?
function save_price(){
alert("started_1"); //just for information
price = document.getElementById('the_id_of_the_textbox').value;
alert(price); //just for information
}
<script type="text/javascript">
function read_price(){
alert("started_2");
alert(price);
}
On "page 1" I have this send-Button with:
<input class="button_send" id="button_send" type="submit" value="Submit_price" onclick="save_price();"/>
It starts the Javascript function and redirects me correctly to my page2.
But with this ont the second page:
window.onload=read_price();
I always get an "undefined" value of the global variable price.
I've read a lot about those global variables. E.g. at this page: Problem with global variable.. But I can't get it working...
Why is this not working?
Without reading your code but just your scenario, I would solve by using localStorage.
Here's an example, I'll use prompt() for short.
On page1:
window.onload = function() {
var getInput = prompt("Hey type something here: ");
localStorage.setItem("storageName",getInput);
}
On page2:
window.onload = alert(localStorage.getItem("storageName"));
You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.
Your best option here, is to use the Query String to 'send' the value.
how to get query string value using javascript
So page 1 redirects to page2.html?someValue=ABC
Page 2 can then
read the query string and specifically the key 'someValue'
If this is anything more than a learning exercise you may want to consider the security implications of this though.
Global variables wont help you here as once the page is re-loaded they are destroyed.
You have a few different options:
you can use a SPA router like SammyJS, or Angularjs and ui-router, so your pages are stateful.
use sessionStorage to store your state.
store the values on the URL hash.
To do this, I recommend sending data within the link data. This is a very simple way of doing it without PHP. Simply get the link in the second page and replace the previous link with "".
Page_One.html:
<script>
//Data to be transfered
var data = "HelloWorld";
//Redirect the user
location.replace("http://example.com/Page_Two.html?" + data);
</script>
Page_Two.html :
<script>
//Get the current link
var link = window.location.href;
//Replace all content before ? with ""
link = link.replace("http://example.com/Page_Two.html?","");
//Display content
document.write("Page_One.html contains:" + link + "");
</script>
Hope it helps!
I have a simple Approach rather (Pure JS):
Page One :
Goto Your Info
Note : You've to encode your GTK value (i.e parameter value) in Base64
Next is Page TWO :
<script>
// first we get current URL (web page address in browser)
var dloc= window.location.href;
//then we split into chunks array
var dsplt= dloc.split("?");
//then we again split into final chunk array, but only second element
//of the first array i.e dsplt[1]
var sanitize= dsplt[1].split("=");
// now here comes the tricky part, join all elements into single //string. IT may be the case, that base64 string contain '=' sign, we shall find it
var dlen= sanitize.length;
var FinString= "";
// we will start from 1, bcoz first element is GTK the key we don't // want it
for(i=1;i<dlen;i++)
{
FinString= FinString+sanitize[i];
}
// afterwards, all the Base64 value will be ONE value.
// now we will convert this to Normal Text
var cleantxt= window.atob(FinString);
document.getElementById("yourname").innerHTML= "Your Name is : <b>"+cleantxt+" .";
You can do anything with the parameter decoded info... Like Redirecting visitor
immediately to another page thru a "POST" method form automatically submitted
by Javasript to Lead a php page finally, without an visible parameters, but with
invisible hidden parms.

Categories

Resources