Change variable value in js from HTML JavaScript? - javascript

I need the community to help me with the following:
I defined the variable x=1 in my js file. I have 2 HTML files that use that variable (1.html and 2.html). I want to use onclick event in 1.html to change the value of variable x to 2 permanently.. so that if I use x variable in 2.html it's value is 2 not 1.
This is what I have in java.js file:
x=1;
This is in 1.html:
<html>
<head>
<script type="text/javascript" src="java.js">
</script>
</head>
<body>
<input type="button" value="Change x" onClick="x=4">
<p id="iz"></p>
</body>
</html>
This is in 2.html:
<html>
<head>
<script type="text/javascript" src="java.js">
</script>
</head>
<body>
<input type="button" value="Change x" onClick="x=x+1">
<p id="iz"></p>
</body>
</html>
The result of the button in 2.html should be 5.

JavaScript doesn't work like that. There's no persistence between pages without using cookies, or passing the state to the server.
If you navigate to foo.html and it sets var foo = 1 and then navigate to bar.html, foo will not have been set.

Short answer, you can't only using JavaScript - the web is stateless.
Though, can use a cookie or local storage as your backing store to hold the value. Initially setting it to 1, any subsequent modifications effect the backing store and reflect the proper value.

In java script there is no persistence of variable as you want, you have to use cookies, a server side aproach or the local storaged offered in html5

This is not normal behaviour for JavaScript because the values you set will on persist for the duration of either page. What you probably want to do is store the value of x on a server, store it in a cookie, or store it in localStorage.

In each of your pages it is pulling in x=1. Just because you change a variable on one page doesn't mean it is going to be seen on another page. This is where you need to pass variables along to the other pages with either GET or POST or cookies or local storage

Your input tags are not closed, that can't be right. Fix these before looking for other reasons for bugs in your code:
<input type="button" value="Change x" onClick="x=4">
Should perhaps be:
<input type="button" value="Change x" onClick="x=4"/>

Related

How to access location attribute of window object?

I have problems with accessing the location attribute of the window object, which I need to redirect the user to another page via JavaScript/jQuery. I know you normally should use an .htaccess file to do this, but I'm actually writing an nw.js application, so I have no server.
Here is an example source code:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-3.2.1.js">
</script>
<script>
$(function() {
$("#testbutton").click(function() {
$("#testbutton).before($(window).attr("location"));
});
});
</script>
</head>
<body>
<button type="button" id="testbutton">Click me</button>
</body>
</html>
This should, if it worked, get the value of the location attribute and insert it before the button when the button gets clicked.
In reality, it doesn't do anything. I also tried to assign the value of the location attribute to a variable, or write this in plain JavaScript (which I intend to avoid), but neither did change the fact that nothing happens.
Is it possible to access the location attribute of the window object via jquery? And if it's possible, what's my mistake?
I wanted to print the value first before changing it, because I like to develop projects step by step. I know this code is not going to change the location attribute, but I wonder why it's not even getting the value?
You don't need jQuery....just access the location.href directly
$(function() {
$("#testbutton").click(function() {
$("#testbutton").before(location.href);
});
});
<script src="//code.jquery.com/jquery-3.2.1.js"></script>
<button type="button" id="testbutton">Click me</button>
The window Object is a global Object and has many properties that you can read and edit , one of this properties is the location Object which is not a text its an object that holds some information about the current location and urls but you can access the current url location using location.href and then you can insert this text any place you want , look at the example below
$(function() {
$('#testbutton').click(function() {
var currentUrl = window.location.href;
$('#testbutton').before(currentUrl+'<br>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button type="button" id="testbutton">Click me</button>
</body>

sessionStorage troubles

I'm trying to understand how sessionStorage works. I get how to make it store some variable and restore it but I wanted to do something different.
This link from w3schools shows how to show/hide elements with a function. I have a pretty similar setup on my site. So I wanted to make it work on the w3schools example then I'll know how to apply it on my site.
Could you perhaps edit the w3schools code to make it use session storage to restore the last option (either shown or hidden) so that I can undestand how it works and apply it then myself?
Thanks in advance.
There you go:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<p id="hideMe">some text</p>
<button id="hide">hide</button>
<button id="show">show</button>
<script>
$(function(){
$("#hide").click(function(){
$("#hideMe").hide()
sessionStorage.setItem('hidden', 'true');
})
$("#show").click(function(){
$("#hideMe").show()
sessionStorage.setItem('hidden', 'false');
})
sessionStorage.getItem('hidden') === 'true' ? $("#hideMe").hide() : null
})
</script>
</body>
</html>
(fiddle)
But I'd say it's not what you're looking for. The sessionStorage will survive page reloads but as soon as you close the tab/window it's gone.
The sessionStorage property allows you to access a session Storage object. sessionStorage is similar to Window.localStorage, the only difference is while data stored in localStorage has no expiration set, data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated, which differs from how session cookies work.
(https://developer.mozilla.org/de/docs/Web/API/Window/sessionStorage)

Passing Variables to a new page without query string

Is there a way to pass a variable from 1 page that has a popup iframe on it to the popup (iframe) on client side button click without using query strings? my variable is too big to use a query string?
Another way to ask the same question
Is there a way to pass a variable from 1 page to another page on client side button click without using query strings? my variable is too big to use a query string?
This is for use on IE 8 and higher html 5 storage will not work
If your two pages are on the same domain, you can use HTML5 LocalStorage. It's a JavaScript object that can hold strings up to around 5MB or so.
If you need to store other data than strings, you can use JSON.stringify() and JSON.parse() to convert between your datatypes and strings.
Without HTML5
You have the option to use cookies and get/set them with JavaScript, otherwise there are many LocalStorage polyfills to choose from which should be able to work in restricted environments.
You can call a function that exists on the child window from the parent and pass data from parent to child.
I apologize for this very basic example, where we pass whatever is in the variable dummy_txt from the parent window to the child window.
Parent (parent.htm)
<html>
<body>
<input id="btn" type='button' value='Open Window' />
<script>
var child_win;
document.getElementById("btn").onclick = function () {
child_win = window.open("child.htm");
dummy_txt = 'blah blah blah blah blah...'
setTimeout(function () {
child_win.document.write(dummy_txt);
// Hey, you can do child_win.my_own_function(dummy_txt)
}, 2000);
}
</script>
</body>
</html>
Child (child.htm)
<html><body></body></html>
Not the cleanest approach, but you can also do something similar to what Nabil suggested by having the child iframe call a javascript function via window.parent
var myValueFromParent = window.parent.SomeFunctionOnParentFrame();
I have used this method not to pass a value from parent to child but rather have child signal parent.
Try the following:
Main Page
<html>
<head>
<title>JS Iframe Test</title>
</head>
<body>
<iframe id="frame" src="js-test-iframe.htm"></iframe>
<br /><br />
<input type="text" id="toInject" /> <button id="send">Send To Iframe</button>
<script type="text/javascript">
document.getElementById('frame').onload = function(){
document.getElementById('frame').contentWindow.doSomething("Hi");
}
var btn = document.getElementById('send');
btn.addEventListener("click", function(){
var text = document.getElementById('toInject').value;
document.getElementById('frame').contentWindow.doSomething(text);
// window.frames[0].doSomething(text); // An alternative
}, false);
</script>
</body>
</html>
IFrame Page (js-test-iframe.htm)
<html>
<head>
<script type="text/javascript">
function doSomething(text)
{
document.getElementById('valueHere').innerHTML = text;
}
</script>
</head>
<body>
<div id="valueHere">Default Text</div>
</body>
</html>
Do keep in mind that you need to wait for the iframe to load before you manipulate or pass any variables to it. Also note that this only works if you are sourcing a page within the same domain.

Javascript change textbox value within iFrame

I'm trying to change the value of a text box within iframe.
I have tried using GetElementById in every way i could find and nothing seems to work.
I found a alternative to iframe by using the Object data tag but it has the same problem.
My code more or less, I changed it a bit for presentation:
<html>
<head>
<title>None</title>
</head>
<body>
<script type="text/javascript">
function changeValue() {
var textBox = document.getElementById('userName');
textBox = "hello!";
}
</script>
<iframe id="myFrame" src="http://www.website.com"></iframe>
<input type="button" onclick="changeValue()" value="Submit">
</body>
</html>
This is not possible for security reasons.
If you had access, you would be able to load, say facebook.com in an iframe on your website and extract user details with JavaScript.
Try something along the lines of
document
.getElementById('myFrame')
.contentWindow
.document
.getElementById('userName')
.value='hello';
As the others pointed out, this will only work if the page inside the iframe is on the same domain.

AJAX returning a javascript to be parsed results in loss of page contents

So I've been working recently on a script to obfuscate client-side code for protecting intellectual property without interfering with the appearance or interactivity of the resulting page. The process is as follows:
HTTP request comes in, .htaccess redirects (.*) to parse_request.php
parse_request.php creates a "phpURLParser" class whose class variables are essentially copies of the $_SERVER variables
phpURLParser looks at the requested path, and sometimes the host, referer, or other server-side information to determine how to react. There are several possible responses
a. The requested object was a .js or .css file. Pass the file to the YUI Compressor and send the output
b. The requested object is an image or application. Pass the file with no change
c. The requested object contains HTML. Replace every ASCII character with its 2-digit hexadecimal equivalent and send the following javascript:
<script type="text/javascript">
var x="~lots of hex~";
var y="";
for(i=0; i<x.length; i+=2){
y += unescape('%'+x.substr(i,2));
}
document.write(y);
</script>
So the website is replaced by a lot of hex and a small javascript to return the hex to its original form. I have an example of this setup at examples.chikachu.com/colorbox/example1 (I didn't code ColorBox, it's a free jQuery tool that I chose to use since it allowed me to test several different javascript features and make sure they all worked)
Now for the problem:
As it turns out, this works 99% of the time. But AJAX makes it angry. Clicking one of the AJAX examples (under "Other Content Types") will look like it redirects you to a new page. Looking in the address bar or viewing the page source will prove that you're still on the same page, however. Using the Inspect Element tool in Chrome (or Firebug in Firefox) will reveal that the contents of the webpage were entirely replaced by the contents of the AJAX request.
If I modify parse_request.php slightly to allow the file requested by the AJAX to be passed through unharmed, everything works. No problem. So for some reason my script which replaces the string of hex with its meaningful HTML counterpart is overwriting the entire website instead of nicely inserting itself within the confines of a <div> object.
Essentially here's the expected non-obfuscated HTML:
<html>
<head>
...
</head>
<body>
<div id="colorbox">
<INSERT AJAX HERE>
</div>
...
</body>
</html>
With only the AJAX obfuscated, I expect the following:
<html>
<head>
...
</head>
<body>
<div id="colorbox">
<script type="text/javascript">
var x="asdfasdfasdfasdf";
var y="";
for(i=0; i<x.length; i+=2){
y += unescape('%'+x.substr(i,2));
}
document.write(y);
</script>
</div>
...
</body>
</html>
I expect that the document.write() line here will write y at the location of the javascript (within the <div>). If I'm mistaken and that's not how document.write() works, I still expect it to write y at the end of the document. Instead, the entire document is replaced by y. Why is this, and what's my solution?
Answer to your last question:
Calling
document.write('my_precious_html_code');
will append or override text on page depending when it was called (before or after onLoad event). You shouldn't use it any script. Read more about it here: http://javascript.crockford.com/script.html
General answer:
Obfuscating HTML code doesn't make any sense. Just like protecting images by disabling right mouse button in late '90. It took me less then 3 sec to "crack" your obfuscated code and get beautifully formatted HTML. Also your site is rendered in quirks mode which is probably something you don't want.
Try something like this:
<html>
<head>
...
</head>
<body>
<div id="colorbox">
<div id="MYAJAXCONTENT">
</div>
<INSERT AJAX HERE>
</div>
...
</body>
</html>
<html>
<head>
...
</head>
<body>
<div id="colorbox">
<script type="text/javascript">
var x="asdfasdfasdfasdf";
var y="";
for(i=0; i<x.length; i+=2){
y += unescape('%'+x.substr(i,2));
}
document.getElementById('MYAJAXCONTENT').innerHTML = y;
// for the jQuery psychos out there
// $('#MYAJAXCONTENT').html(y);
</script>
</div>
...
</body>
</html>

Categories

Resources