I have 2 HTML pages, send.html and receive.html
In each page I have a textield. The thing that I'm trying to do is whenever the "value" of the textfield in the send.html changes, automatically parse the data to the textfield value of the receive.html. When I say automatically I mean without the need of a button or reloading the pages.
To sum up.. I have this textfiled in the send.html
<input type="text" id="send" size="25" value="Val1">
And this text field in the receive.html
<input type="text" id="receive" size="25" value="Val2">
I want to "monitor" somehow the Val1, and if it changes I want Val2=Val1
For my purpose I cant use jquery.
Is that possible?
I think you are missing a big picture. Data sending and receiving needs some server side interaction like using PHP, ASP, JSP, Python etc., unless you are ok with cookies.
When you update a field in one age, that data needs to go the server somehow for another page to catch. Either way, the way you want it to go automatic is not possible right now. However, I will provide a solution of how you can do this using jQuery and PHP. But if you want?
Update
So, it seems cookies is the only option. Follow the following steps
Create a new file cookie.js and place the following code inside
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
Next, create two html file "test1.html" and "test2.html" with this markup
<html>
<head>
<script src="cookie.js"></script>
</head>
<body>
<input type="text" id="text1" name="text1" />
</body>
</html>
Now, on test1.html add the following script on the head
<script>
window.onload = function() {
document.getElementById("text1").onchange = function() {
// ^ use onkeyup if you want this to occur as you type
setCookie("shared", this.value, 1);
alert('oK, val changed so lets check it');
};
};
</script>
On Test2.html add the following Script on the head
<script>
var checkandupdate = function() {
var shared = getCookie("shared");
if(shared) {
document.getElementById("text1").value = shared;
}
};
window.onload = function() {
int = setInterval("checkandupdate()",1000);
};
</script>
Now
Open both pages
Go to test1.html and type something then press tab to get the alert message.
Open the test2.html, it should be update within 1 second
After the demo works, Update the field names as you need
Enjoy ;)
In your second HTML page , let's say we call it like page-2.html?send=xyz when the value is being changed , you add the following JS Code :
function getQueryString() {
var result = {}, queryString = location.search.substring(1),
re = /([^&=]+)=([^&]*)/g, m;
while (m = re.exec(queryString)) {
result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
return result;
}
var sendValue= getQueryString()["send"];
document.getElementById("receive").value=sendValue;
if you want to use without cookie for improving the performance.. you can use this library it uses window.name to carry the values.. however it will not work if the user opens in new tab.. still it is good.. only thing is you should handle new tab situation..
Hope this helps.. especially it will help if it is a html based front end..
Related
I currently have a sitation where I can click on an image and it will return a new image, and in the previous grid-item, it will return the day and time I clicked it.
What I want is to have this BUT where I also can see the updated image and clicked time after closing and re-opening the browser. - What is the easiest / quickest way to achieve this?
I feel like adding to my database would be a way forward, but if that is what I would need to do, how would I go about storing and out-putting the time based on the time I click?
(This is not intended to be a live site, or for others to see or use, so local quick-fixes are viable).
foreach ($flavours as $key => $flavour) {
echo "<div class='grid-container'>";
echo "<div class='item7'><p id='p3'>Sylus: </p></div>";
echo "<div class='item8'><img src='htts://i.i.com/k.jpg' onclick='cS(this)' /></div>";
echo "</div>";
}
function cS(element) {
if (element.src == "htts://i.i.com/k.jpg")
{
element.src = "http://i.i.com/v.jpg";
var d = moment().format('dddd HH:mm');
element.parentElement.previousElementSibling.firstChild.innerHTML = "Sylus: " + d;
}
else
{
element.src = "htts://i.i.com/k.jpg";
element.parentElement.previousElementSibling.firstChild.innerHTML = "Sylus: ";
}
}
Try this example using localStorage. This will find the <p> tag elements within the body, and then uses each element to get the id for reference.
I tried using a fiddle here, but the site has a security complaint with the localStorage.
Copy/paste this code to a file to give it a try. Note that you will likely need to update the moment.js reference in this code to match your file path.
<!doctype html>
<html>
<head>
<title>localStorage example</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="moment.js"></script>
</head>
<body>
<div class='grid-container'>
<div class='item7'><p id='p0'>Sylus: </p></div>
<div class='item8'><img src='htts://i.i.com/k.jpg' onclick='cS(this)' /></div>
</div>
<div class='grid-container'>
<div class='item7'><p id='p1'>Sylus: </p></div>
<div class='item8'><img src='htts://i.i.com/k.jpg' onclick='cS(this)' /></div>
</div>
<script>
function cS(element) {
var pTag = element.parentElement.previousElementSibling.firstChild;
if (element.src == "htts://i.i.com/k.jpg")
{
element.src = "http://i.i.com/v.jpg";
var d = moment().format('dddd HH:mm');
var pText = 'Sylus: ' + d;
pTag.innertHTML = pText;
// Set (save) a reference to browser localStorage
localStorage.setItem(pTag.id, pText);
}
else
{
element.src = "htts://i.i.com/k.jpg";
pTag.innerHTML = "Sylus: ";
// Remove the stored reference. (delete this if not needed)
localStorage.removeItem(pTag.id);
}
}
$(document).ready(function() {
pElements = $('body').find('p').each(function(index, element) {
// Get the localStorage items. The retrieved <p> elements,
// we use their id value to reference the key in storage.
storageItem = localStorage.getItem(element.id);
if (storageItem) {
$('#' + element.id).text(storageItem);
}
});
});
</script>
</body>
</html>
After clicking an image (will need to replace with something real), open the browser's web inspector interface, click the Storage tab, and then expand the Local Storage in the list (see image below), and choose the file being tested.
There will be key/value pairs displayed. The keys are references to the <p> tag id's, and the value will have a label-date strings such as Sylus: Wednesday 22:28.
Once you see an entry, or two, being set to the storage, close and then reopen the browser tab. The <p> elements that had dates should be reloaded with their values from the storage.
The browser's Local Storage area should be similar to the image below:
save it to local storage, or a cookie with the exp. date too far in the future
I have done a lot of research on how to do this, yet I can't seem to find a specific answer. I am trying to allow the user to input a file from their computer, and turn that file into the background of the webpage. My following code is shown below:
<head>
<script>
function changeBackground() {
var input = document.getElementById("background").value;
localStorage.setItem("Background", input);
var result = localStorage.getItem("Background");
$('body').css({ 'background-image': "url(" + result + ")" });
}
</script>
</head>
<body>
<input id="background" type="file" onchange="changeBackground()">
</body>
If someone could please explain to me what I need to do to get this to work, I would very much appreciate it. I already understand I need to use localStorage to make sure that the selected background is remembered, I am just having trouble getting the background to change. If there is already an article on how to do this, I would appreciate a link to it. Thanks!
EDIT
Nikhil and user6003859 explained to me why it isn't working. I guess I just need to figure out how to use Ajax and PHP to change it. If anyone has more advice on this, I would love to hear it. Thanks everyone for helping me solve this problem.
Modern browsers normally restrict access to the user's local files (in this case an image). What you're trying to do is display an image from the user's local filestorage, via the path you get from the <input type='file' /> value.
What you should instead be doing, is uploading the image to your server (probably with ajax, so it feels seamless), and then displaying the file from your server on to your page.
EDIT: Even though this is kind of a new question, I'll give you an example on how to change an element's background based on a URL provided by the user:
var inp = document.getElementById('inp');
var res = document.getElementById('res');
inp.oninput = function()
{
res.style.backgroundImage = 'url(' + inp.value + ')';
};
div
{
width: 5em;
height: 5em;
}
<input type='text' id='inp' />
<div id='res'>
</div>
It's better practice to use file reader.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#file").change(function(){
var length=this.files.length;
if(!length){
return false;
}
changeBackground(this);
});
});
// Creating the function
function changeBackground(img){
var file = img.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2]))){
alert("Invalid File Extension");
}else{
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(img.files[0]);
}
function imageIsLoaded(e) {
$('body').css({ 'background-image': "url(" + e.target.result + ")" });
}
}
</script>
</head>
<body>
<input type="file" name="" id="file" value="Click">
</body>
</html>
You cannot do that purely with client-side because of security reasons.
The moment you upload say an image, the browser gives it a "fakepath" like so:
C:\fakepath\<filename>.png
This is a security implementation of the browser - the browser is protecting you from accessing your disk structure.
Hence when you check the value of your input after uploading, you would get the above fakepath ie. C:\fakepath\<filename>.png. Using this as the background obviously would not work.
Usually to achieve this you need to first store it in a server, then fetch the value from the server and apply the background.
To use a local file, store it in a blob
<head>
<script>
function changeBackground() {
var backgroundFile = document.getElementById("background").files[0];
$('body').css({ 'background-image': "url(" + URL.createObjectURL(backgroundFile) + ")" });
}
</script>
</head>
<body>
<input id="background" type="file" onchange="changeBackground()">
</body>
Let's say I have an xml file I want to upload through a html form using php but I want to verify first that the xml file is an actual file using javascript. I have a form with only one input and this piece of javascript code:
function Validate(form) {
var _validFileExtensions = [".xml"];
var arrInputs = form.getElementsByTagName("input");
for (var i = 0; i < arrInputs.length; i++) {
var oInput = arrInputs[i];
if (oInput.type == "file") {
var sFileName = oInput.value;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if (!blnValid) {
alert(oInput.type);
//alert("Lo siento, " + sFileName + " es invalido, la única extensión permitida es: " + _validFileExtensions.join(", "));
return false;
}
}
}else{
alert(oInput.type);
//alert("Tienes que seleccionar un archivo");
return false;
}
}
return false;
}
I'm just putting this piece to describe the problem, which is that file.xml isn't a file, is empty, if I try to submit any type of file that I can find on my computer, like "javascript.js", "newdocument.txt" or any kind of file, javascript "file.type" does match "file", but if I submit a "file.xml" it alerts "submit", same thing if I click submit without selecting any file. Which leads me to believe that .xml files are treated as some kind of instruction or something.
I know I also have to validate server side and stuff, but for now I want to validate client side using javascript, so, is there a way to validate that "file.xml" is a file?
EDIT: (Added full code and fiddle>
HTML:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="content-type" />
<title>XML a PDF</title>
<script type="text/JavaScript" src="javita.js"></script>
</head>
<body>
<form action="transforma.php" method="post" mimetype="text/xml" enctype="text/xml" onsubmit="return Validate(this);" name="transforma">
<label for="file">Filename: </label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Also tried with:
<form action="transforma.php" method="post" enctype="multipart/form-data" onsubmit="return Validate(this);" name="transforma">
Same result
Fiddle
If you have not realized it yet, you're just totally looking in the wrong direction with the assumptions you do.
First of all, javascript does not differ on the contents of a string here. It just operates on a string. Whether that string contains "I hate you javascript, go home" or "this-file-extension-is-better-than-others.txt" or your so missing "file.xml" - it will always work the same here.
See this comment of yours two days ago:
I'm more interested on knowing is why a xml file isn't recognized as a file by javascript, or how can I accomplish javascript to acknowledge a xml file as a file.
So I let you know: The XML file is recognized as a file by javascript.
After I have introduced that knowledge to you (and I hope you're openhearted accepting this to know, too, as it solves the largest part of your problem), then let's see what's going on here.
First of all you're doing too many things at once. For example, you'd like to get the file input element. As it doesn't have an ID you iterate through all inputs. That's just not necessary. If the problem is that the element can't well be identified, give the form an ID so that you can:
form.id || (form.id = "id".concat(+new Date, parseInt(Math.random() * Math.pow(10, 16))));
var fileName = document.querySelector("#".concat(form.id, " input[type=file]")).value;
Done. There is the string of the fileName. If you then verify this, you can easily see that it always contains the filename. If not yet choosen, it's an empty string, if choosen, it's the "fakepath" string of the filename. At least at this point you have to realize that it always will be a string, regardless of which file you've been chosen.
Next thing is that you should create a function that validates a filename's extension against your whitelist. This has the benefit, that you can just use it on any string no matter where you got it from:
var fileExtension = function (file) {
var extensions = [".xml"];
var match;
extensions.every(function (extension) {
var e = /([.*+?^=!:${}()|\[\]\/\\])/g;
if (new RegExp(extension.replace(e, "\\$1") + '$', 'i').test(file)) {
match = extension;
return false;
}
return true;
});
return match;
}
When done this, you can easily validate the form, see this working fiddle: http://jsfiddle.net/JZj85/
It's not entirely foolproof but you could try this:
function validate(form) {
var file = form.getElementsByTagName("input")[0];
var ext = file.value.substring(file.value.lastIndexOf('.'));
if (ext == "xml") {
// Do something when it is an xml file
} else {
// Do something else when it is not
}
return false
}
.getElementsByTagName returns an array of elements. You want the first one since that is your file input.
var ext = ... gets the extension, or at least what is behind the last . (including). But a user can still upload another filetype but just change the extension, so you need some serverside validation as well.
See Fiddle
How can I read the client's machine/computer name from the browser?
Is it possible using JavaScript and/or ASP.NET?
You can do it with IE 'sometimes' as I have done this for an internal application on an intranet which is IE only. Try the following:
function GetComputerName() {
try {
var network = new ActiveXObject('WScript.Network');
// Show a pop up if it works
alert(network.computerName);
}
catch (e) { }
}
It may or may not require some specific security setting setup in IE as well to allow the browser to access the ActiveX object.
Here is a link to some more info on WScript: More Information
Browser, Operating System, Screen Colors, Screen Resolution, Flash version, and Java Support should all be detectable from JavaScript (and maybe a few more). However, computer name is not possible.
EDIT: Not possible across all browser at least.
Well you could get the ip address using asp.net, then do a reverse DNS lookup on the ip to get the hostname.
From the ASP.NET Developer's cookbook ... Performing a Reverse-DNS Lookup.
It is not possible to get the users computer name with Javascript. You can get all details about the browser and network. But not more than that.
Like some one answered in one of the previous question today.
I already did a favor of visiting your website, May be I will return or refer other friends.. I also told you where I am and what OS, Browser and screen resolution I use Why do you want to know the color of my underwear? ;-)
You cannot do it using asp.net as well.
Try getting the client computer name in Mozilla Firefox by using the code given below.
netscape.security.PrivilegeManager.enablePrivilege( 'UniversalXPConnect' );
var dnsComp = Components.classes["#mozilla.org/network/dns-service;1"];
var dnsSvc = dnsComp.getService(Components.interfaces.nsIDNSService);
var compName = dnsSvc.myHostName;
Also, the same piece of code can be put as an extension, and it can called from your web page.
Please find the sample code below.
Extension code:
var myExtension = {
myListener: function(evt) {
//netscape.security.PrivilegeManager.enablePrivilege( 'UniversalXPConnect' );
var dnsComp = Components.classes["#mozilla.org/network/dns-service;1"];
var dnsSvc = dnsComp.getService(Components.interfaces.nsIDNSService);
var compName = dnsSvc.myHostName;
content.document.getElementById("compname").value = compName ;
}
}
document.addEventListener("MyExtensionEvent", function(e) { myExtension.myListener(e); }, false, true); //this event will raised from the webpage
Webpage Code:
<html>
<body onload = "load()">
<script>
function showcomp()
{
alert("your computer name is " + document.getElementById("compname").value);
}
function load()
{
//var element = document.createElement("MyExtensionDataElement");
//element.setAttribute("attribute1", "foobar");
//element.setAttribute("attribute2", "hello world");
//document.documentElement.appendChild(element);
var evt = document.createEvent("Events");
evt.initEvent("MyExtensionEvent", true, false);
//element.dispatchEvent(evt);
document.getElementById("compname").dispatchEvent(evt); //this raises the MyExtensionEvent event , which assigns the client computer name to the hidden variable.
}
</script>
<form name="login_form" id="login_form">
<input type = "text" name = "txtname" id = "txtnamee" tabindex = "1"/>
<input type="hidden" name="compname" value="" id = "compname" />
<input type = "button" onclick = "showcomp()" tabindex = "2"/>
</form>
</body>
</html>
There is no way to do so, as JavaScript does not have an access to computer name, file system and other local info. Security is the main purpose.
No this data is not exposed. The only data that is available is what is exposed through the HTTP request which might include their OS and other such information. But certainly not machine name.
<html>
<body onload = "load()">
<script>
function load(){
try {
var ax = new ActiveXObject("WScript.Network");
alert('User: ' + ax.UserName );
alert('Computer: ' + ax.ComputerName);
}
catch (e) {
document.write('Permission to access computer name is denied' + '<br />');
}
}
</script>
</body>
</html>
There is some infos to parse into the webRTC header.
var p = new window.RTCPeerConnection();
p.createDataChannel(null);
p.createOffer().then((d) => p.setLocalDescription(d))
p.onicecandidate = (e) => console.log(p.localDescription)
An updated version from Kelsey :
$(function GetInfo() {
var network = new ActiveXObject('WScript.Network');
alert('User ID : ' + network.UserName + '\nComputer Name : ' + network.ComputerName + '\nDomain Name : ' + network.UserDomain);
document.getElementById('<%= currUserID.ClientID %>').value = network.UserName;
document.getElementById('<%= currMachineName.ClientID %>').value = network.ComputerName;
document.getElementById('<%= currMachineDOmain.ClientID %>').value = network.UserDomain;
});
To store the value, add these control :
<asp:HiddenField ID="currUserID" runat="server" /> <asp:HiddenField ID="currMachineName" runat="server" /> <asp:HiddenField ID="currMachineDOmain" runat="server" />
Where you also can calling it from behind like this :
Page.ClientScript.RegisterStartupScript(this.GetType(), "MachineInfo", "GetInfo();", true);
Erm is there any reason why you can't just use the HttpRequest? This would be on the server side but you could pass it to the javascript if you needed to?
Page.Request.UserHostName
HttpRequest.UserHostName
The one problem with this is it would only really work in an Intranet environment otherwise it would just end up picking up the users Router or Proxy address...
I want to POST form values and display them on another html page using Javascript. No server-side technology should be used. I have a function that posts the values but to read the values to another html page, I think I am missing something. Below is the code.
Any help? Thanks in advance.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script type="text/javascript">
function post_to_page(path, params, method) {
method = method || "post"; // Set method to post by default, if not specified.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
form.setAttribute("target", "formresult");
for (var key in params) {
if (params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
// creating the 'formresult' window with custom features prior to submitting the form
window.open('target.htm', 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');
form.submit();
}
</script>
</head>
<body>
<form id="form1" action="target.htm" method="post">
<div>
USB No: <input name="usbnum" id="usbnum" type="text"/><br />
USB Code: <input name="usbcode" id="usbcode" type="text"/>
</div>
<button onclick="post_to_page()">Try it</button>
</div>
</form>
</body>
</html>
Here is a simple example of moving data from one Window to another
<!-- HTML -->
<textarea id="foo"></textarea><br/>
<input id="bar" value="click" type="button"/>
and the real code to make it work, which assumes you pass the same origin policy
// JavaScript
var whatever = 'yay I can share information';
// in following functions `wnd` is the reference to target window
function generateWhatever(wnd, whatever) { // create the function actually doing the work
return function () {wnd.document.getElementById('foo').innerHTML = whatever};
} // why am I using a generator? You don't have to, it's a choice
function callWhenReady(wnd, fn) { // make sure you only invoke when things exist
if (wnd.loaded) fn(); // already loaded flag (see penultimate line)
else wnd.addEventListener('load', fn); // else wait for load
}
function makeButtonDoStuff() { // seperated button JS from HTML
document
.getElementById('bar')
.addEventListener('click', function () {
var wnd = window.open(window.location); // open new window, keep reference
callWhenReady(wnd, generateWhatever(wnd, whatever)); // set up function to be called
});
}
window.addEventListener('load', function () {window.loaded = true;}); // set loaded flag (do this on your target, this example uses same page)
window.addEventListener('load', makeButtonDoStuff); // link button's JavaScript to HTML when button exists
You can't get POST values using JavaScript. You can use GET method to pass values.
If you are using html5 you can use localStorage. Otherwise a query string or cookies are your other options.
You said you didn't want the server involved...why are you calling submit?
[Edit]
#Paul S's comment/answer looks very helpful. But you might look at something like the jQuery PostMessage plugin if you need it to be cross browser compatible.
http://benalman.com/projects/jquery-postmessage-plugin/
You don't require a POST request to send data from one page to another. Simply use LocalStorage to do the trick. Just call a Javascript function on form submission. This may help:
HTML:
<form id="form1" action="target.htm" method="post">
<div>
USB No: <input name="usbnum" id="usbnum" type="text"/><br />
USB Code: <input name="usbcode" id="usbcode" type="text"/>
</div>
<button onclick="post_to_page()">Try it</button>
</form>
Javascript:
function post_to_page() {
localStorage.value = "Your content here";
window.location = "nextpage.html";
}
This will save the data locally and go to the next page. In the next page, simply call this function to retrieve the stored data:
function get_stored_data() {
alert(localStorage.value);
}
You can simply assign it to a div, textbox other Javascript variable.