I am creating a website in plain HTML, CSS and JavaScript and want to send data between two pages (child and parent). Here is a simple example of what I want to do.
CHILD PAGE:
<html>
<head>
<title>Child</title>
</head>
<body>
<input type='text' placeholder='Enter data to be sent.' id='data'>
<button onclick='work()'>Send</button>
<script>
function work(){
var data = document.getElementbyId('data').value
//Code to send this data to parent.
}
</body>
</html>
PARENT PAGE:
<html>
<head>
<title>Parent</title>
</head>
<body>
<h1 id='data_recieved'></h1>
<button onclick='work()'>Recieve</button>
<script>
function work(){
var data = document.getElementbyId('data_recieved').innerHTML;
//Code to receive the data from child
}
</body>
</html>
I will be very grateful for your help.
DOM don't work across pages. You have to use a storage medium, it can be client side i.e localStorage, 'sessionStorage' or cookies using JavaScript. Or you can use a backend where you can store the values in some sort of database.
Another way to pass data from one page to another is to use a <form>, fill in certain fields and submit it so that it gets sent as POST or GET data to the next page. In your case I believe this should be the ideal scenario. If you do not have a backend best option is to send form data using GET method so that it gets appended to the URL as query parameters.
e.g on parent HTML page
<form action='child.html' method='get'>
<input type='text' name='somedata' value='whatever'/>
<input type='submit'/>
</form>
and on child page you can use JavaScript to get the query parameters using JS
<script>
var somedata = getParameterByName('somedata');
function getParameterByName(name, url = window.location.href) {
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
</script>
There are of course other more sophisticated and advanced ways to achieve the same results but those might not be what you are looking for.
Sending data to a page doesn't mean anything, you have to send data to a program or to a server that will be able to interpret this data.
The easiest way is to send an HTTP request to the server, either by ajax if you don't want the navigator to close the page, or by just sending the form or requesting a link. You can then interpret the request using any program you want (PHP being one of the most used option).
Firstly, I noticed that your <input /> tag is missing the / to self close.
You will need to add a Javascript file to your project. Import the file into both html pages using a <script> tag.
You can get rid of the work() functions in both pages. Rather, you will store the onClick events in the Javascript file. Additionally, you will have a data object in the Javascript file that will store the data when the 'sent' button is clicked and retrieve it when the 'receive' button is clicked.
Add an id to the 'send' button on the child page:
<button id="send-button">Send</button>
In the Javascipt file:
let data = ''; //data will start off as an empty string
$("send-button").on('click', function(){
data = $("data").val(); //gets the data from your <input /> on the child page
})
Now add an id to the 'receive' button on the parent page:
<button id="receive-button">Receive</button>
And back to the Javascript file where the data will be stored in the data object:
$("receive-button").on('click', function(){
$("data-received").val(data); //changes the value of the <h1> to be the data
})
Related
Am new to coding and learning Python. Currently working on Flask to make some webapp. For one of the project I am trying to achieve the below
(1) On a webpage , I have a button when clicked, I pass the values inside the textbox to Python function. Which does some operation of getting the data from the database and it create an html which stores that database query output into a table.
(2) When this HTML file is generated with the table inside, I want to display the same in my webpage in an iframe (the page generates iframe automatically)
The way I have achieved this is having 2 buttons, One button to pass the values to Python function and second button to display the generated HTML into an iframe.
<br />
<input type='submit' value='Process Query' class="savebtn" name='Submit' />
<br />
<input type='button' value='Submit Query' class="savebtn" name='Submit' onclick="myFunction()" />
. . .
<script>
function myFunction() {
var iframe = document.createElement('iframe');
$('iframe').not(this).remove();
var html = '
<body>Foo</body>';
iframe.src = 'http://192.xx.xx.xx:10000/Table.html';
iframe.height = "500";
document.body.appendChild(iframe);
console.log('iframe.contentWindow =', iframe.contentWindow);
}
</script>
I think the second button is unnecessary but am not sure how can I do this?
Apologies if this is found too basic for many but as i said , am starting to learn coding.
If I understand your problem correctly, what you want is to first process the text and generate some html, and then display this same html to a user. If that is the case, what you need is an asynchronous request.
With an asynchronous request, you send data off to the server (without reloading the web page) and when you receive a response, you do something with it. A very crude code would be something like
function clickButton(){
fetch("/<path_to_server>/")
.then(function(result) { // This is the response from the server
return result.json(); // convert it to json
})
.then(function(data) {
// process your returned data
// e.g. data.generated_table could be your html output
// which you can now display in your iframe
})
}
Hmm is it possible to document.write on other html page?
For example I create a two html page, the first page have a textfield and submit button. I enter a text in a textfield and after I click the submit button the value of the textfield will be transfer to the second html page and load the html page and write the value on it.
Just a beginner to javascript so bear with me please :D
You can do this by using Query String.
window.location = "Pass.aspx?variabletopass=test";
Use this line of where you are trying to redirect your page,and value of your textfield in query string.
Since you're using pure javascript and HTML, I assume server-side things are out of the picture. So Felix Kling's comment is actually, I think, a good way to go. Here's one way you could use localStorage to make this work:
/* index.html */
<form action="result.html" onsubmit="submit()">
<input type="text" id="input">
<input type="submit" value="Submit">
</form>
<script>
function submit() {
var input = document.getElementById("input").value;
localStorage.input = input;
}
</script>
/* result.html */
<div id="result"></div>
<script>
document.getElementById("result").innerHTML = localStorage.input;
</script>
Without using php you can document.write() submitted text on other html file as follows.
<html>
<script>
var a = document.location.toString();
var b = a.slice(a.indexOf("?")+1,a.length);
var c = b.split("&");
for(i=0;i<c.length;i++){
document.write(c[i]);
}
</script>
</html>
If you are working on Single page Application you can quite easily achieve this, by just storing the value in correct scope.
If you are on multiple page application you can achieve this by any of the following ways:
sending parameter in url
storing value in localStorage/sessionStorage
storing it in cookie(Not recommended)
sending it to server in forms param(Not recommended)
I am trying to create a new HTML page from a form and some javascript. The form is much longer than this, but I figured that if I gave you guys 2 text inputs I can take it from there. I am running into a problem where I cannot retrieve the value of my forms and send it on to my new page. My new page won't show anything because it thinks that my forms are null, or that they don't exist possible. Which is probably why it returns undefined. I'm completely stuck here and I have no idea what to do as far as setting up the new page from my form goes.
I need help with getting newPage.html to display my title and subtitle.
Here is js:
var title = document.createElement("h1");
var titleForm = document.getElementById("title");
var subTitle = document.createElement("h3");
var subtitleForm = document.getElementById("subtitle");
var myDiv = document.getElementById("container");
function getElements() {
//set the title
var titleNode = document.createTextNode(titleForm.value);
title.appendChild(titleNode);
//set the subtitle optionally
var subtitleNode = document.createTextNode(subtitleForm.value);
subTitle.appendChild(subtitleNode);
}
Here is the original HTML page:
<body>
<h1>Create A New Webpage Using This Form</h1>
<form id="form">
<label>
Title:
<input type="text" name="title" id="title" value="title">
</label><br><br>
<label>
Subtitle:
<input type="text" name="subtitle" id="subtitle" value="subtitle">
</label><br><br>
<input type="button" value="Generate Page" onclick="window.open('newPage.html');">
</form>
<script type="text/javascript" src="pageGenerator.js"></script>
<script>getElements();</script>
</body>
Here is the page that I want to create:
<body>
<div id="container">
<ul id="myList"></ul></div>
<script type="text/javascript" src="pageGenerator.js"></script>
<script>setElements();</script>
</body>
I'm not looking for you to complete this for me, but just a little bit of guidance. Thanks.
It sounds like you want JavaScript on one page to read from JavaScript on another page. That's not possible on its own. You can't define var a = 1 on somePage.html then read that variable when the user's browser loads newPage.html.
You'll need to involve something else, such as the URL or local storage: https://stackoverflow.com/a/35027577/5941574
Query Parameters
One option is to make a GET request to newPage.html with whatever values you want include as query parameters in the request. Then newPage.html will contain a script that parses the URL to get the parameters and builds and inserts HTML into the document based on the values it finds in the URL.
Local Storage or Cookies
This works in pretty much the same way as the other method except instead of getting your values from the URL, it is saved to the user's computer with either cookies or local storage.
Server Side
A third option of course is to send the user's selections to a server and have the server build and serve the resulting page.
I've read a few articles and a question thread on sending form data to another html page, but the solutions didn't solve the issue for me.
Basically, I have a form with a bunch of data:
<form id="registration" name="registration" action="register.html" method="POST">
In register.html, I tried accessing an input text field with id and name as "username" with this:
var x = document.getElementById("registration").elements.namedItem("username").value;
The console stated that it cannot read property of null. How can I access these values with Javascript only? Frameworks are fine but not PHP /Python.
I'm sure that none of this can be safe, so use caution.
If you don't care about the info being super obvious, then you can make the action of the the form the new page you want, and the method can be 'GET'.
EDIT: I should mention this will go through the url, as such
domain.com?someKey=someValue&someOtherKey=someOtherValue
On the new page, you can parse the url for the query string for everything.
You can grab that stuff out of the 'href' property from the location.
window.location.href
// * Credit for this puppy goes to theharls, nice and fast
var params = window.location.search.slice(1).split("&");
//=> ["say=Hi", "to=Mom"]
Another option on (modern ?) browsers is Local Storage.
Use javascript to to set things like,
localStorage.setItem('foo', 'bar');
Great reference for local storage here.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
I ran into something like this the other day. Turns out you can just get the values with jQuery.
var userName = $("input[type=text][name=username]").val();
Just put it into a function that's called in the form's onsubmit.
<script>
function getFormData() {
var userName = $("input[type=text][name=username]").val();
// Do what you want with the data
return true;
}
</script>
<form id="registration" name="registration" action="register.html" onsubmit="return getFormData();" method="POST">
<input type="text" name="username" />
</form>
However, this doesn't keep the data when you load the next page. To do that, just commit the value into sessionStorage.
function saveFormData() {
var userName = $("input[type=text][name=username]").val();
sessionStorage.setItem("user", userName);
return true;
}
And then on the next page (the one you're calling resgister.html) you can use this code to retrieve it.
var userName = sessionStorage.getItem("user");
I hope this helps!
A webpage can't receive POST data. Send it using method="GET" instead, then retrieve it on the target page using JS as follows:
<script>
var params = window.location.search.slice(1).split("&");
// params is ["say=Hi", "to=Mom"]
</script>
You can easily target the selectors by querySelector. The value will no longer be null.
<form id="registration" name="registration" action="register.html" method="POST">
<input type="text" class="username" value="abcdefg">
</form>
<script>
var x = document.querySelector("#registration .username").value;
//check your code in devtools
console.log(x);
</script>
jsfiddle
Good day all, I've two pages of php file and an external javascript file. I want to pass a selected radio button's value to a jquery global variable so that I can view the div element which has the same id as selected radio button's value. Whenever I click PLAY! button I don't see my div element on the next page. Here are my codes:
player-choose.php script:
<head>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/mycustom.js"></script>
</head>
<body>
<div id="player-list">
<input type="radio" name="player" value="fighter" id="fighter-radio"><label for="fighter-radio"><img src="images/heroes/fighter-01.png" width="74" height="70"></label>
<input type="radio" name="player" value="pakhi" id="pakhi-radio"><label for="pakhi-radio"><img src="images/heroes/pakhi.png" width="95" height="70"></label>
</div>
<button id="play">PLAY!</button>
</body>
mycustom.js script:
var playerID;
function start(){
spawnhero();
}
$(function(){
$("#play").click(function(){
window.location.href = 'index.php';
playerID = $('input[name=player]:checked').val();
});
})
function spawnhero () {
$("#content").append($("<div>").attr('id', playerID));
}
index.php script:
<head>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/mycustom.js"></script>
</head>
<body onload="start()">
<div id="content">
<div id="galaxy"></div>
</div>
</body>
It's a very simple thing but I don't know why it's not working. Am I doing something wrong here? Please if anyone finds a solution enlighten me. Tnx!
If you're moving to a new page (window.location = ...), you'll need some slightly more complicated way of transferring information between those pages - for the most part, HTTP/HTML is "stateless", with the exception of technologies like cookies. JavaScript variables get wiped out entirely - it's actually re-parsing the entire JQuery library on each new page (not to say that's something to avoid)
For a video game, as long as player information doesn't include server components (I could be wrong) my recommendation would be saving player information in sessionStorage.
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
However, if this is a server-based game in which your choice of player matters beyond the local computer, you'd likely want to send the player ID to the server, either by structuring the page request differently:
window.location.href = 'index.php?playerId=' + playerId;
Or by POSTing the data as a form; most easily accomplished by structuring your submit button as an <input type="submit">, and wrapping all your <input> elements in a <form method="POST"> object.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form
From there, your server software could write the second page's response out differently based on the given information - you can even customize what JavaScript is written inside of a <script> tag using PHP directives.
var playerId = "<?php print($_POST['playerId']); ?>";
Hopefully that helps get you started.
global variables are not persistent across pages. Once you load your index.php , it will have the new global scope(window variable).
I suggest passing a parameter.
$("#play").click(function(){
playerID = $('input[name=player]:checked').val();
window.location.href = 'index.php?id=' + playerID;
});
afterward, inside your index.php script , read the parameter and assign accordingly.
Alternative solution is you could you use JavaScript or jQuery cookie or localstorage. You can get/set values across page loads/redirects but these are not passed to server.
jQuery Cookie
var playerID = $('input[name=player]:checked').val();
$.cookie("playerId", playerID);
LocalStorage
var playerID = $('input[name=player]:checked').val();
localStorage.setItem("playerId", playerID);