Having problems with my very basic HTML static page generator - javascript

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.

Related

How to pass data to parent in JavaScript and HTML

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
})

Retrieve variable name from an HTML site

I am trying to retrieve simple javascript variable (which is written to a File Systems Object) from a website which is served by an apache host on my ubuntu laptop.
So I have the function that writes the variable set up as follows:
<script type ="text/javascript">
function WriteToFile(passForm) {
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("/home/lex/Downloads/goal.txt", true);
s.writeline(document.passForm);
s.Close();
}
</script>
and the section that takes the user input from the html website is
<div id="bot-right">
<form onsubmit="WriteToFile(this['goal'].value)">
<a align = "left"> <b><Strong>Enter a Goal name</Strong></b></a><br>
<input type="text" name="goal"> <br>
<input type="submit" value="Send Zeus">
<br>
</form>
</div>
For some reason, when I type in variable names to the form on the website, the file goal.txt gets created in the directory, /home/lex/Downloads/, but nothing gets written to it.
I also noticed that when I delete the goal.txt file and rewrite the variable from the html website, the file doesn't always get created.
I am not a JavaScript person and I am at a loss as to what I may need to fix this.
My intention is to get the variable written to the text file and have a processing c++ file process the variable.
Would someone be kind enough to lend an insight?
Thanks!
one way to do it is just calling the function without parameters and just getting the input value like this:
adding and id or a class to your input to get that specific value:
document.getElementById('goal').value
document.getElementByClass('goal').value
Or getting the value by name:
document.querySelector('[name="goal"]').value;
EDIT1
You could add a console.log to check if the value is beign passed correctly like this:
var inputValue = document.querySelector('[name="goal"]').value;
console.log(inputValue);
And if the value is being passed then the problem is your writeline or in the creation of the document
EDIT2
I just tested it and retrieving the value works just fine, so the problem must be in your document writing method, please check this documentation it can help you and i think is a better solution:
http://www.html5rocks.com/en/tutorials/file/filesystem/

Open Google page in Javascript

I have the following code to open a google page and type "Hello" in the textbox.
The code opens the page but the textbox is empty.
Does anyone have an idea please ?
Thanks.
<html>
<head>
<script type="text/javascript">
function getValue()
{
var myWindow = window.open("http://www.google.com","_self")
myWindow.title = "Test"
var TextBox = myWindow.document.getElementsByName("lst-ib");
TextBox[0].value="Hello"
}
</script>
</head>
<body>
<form>
<input name="to" type="hidden" value="hoolah" />
<input type="button" onclick="getValue()" value="Get Value!" />
<form/>
</body>
</html>
You cannot:
Access the DOM of a page on a different origin
Access the DOM of a page from JavaScript that was running in the same window before you loaded the new page
What you want is impossible.
(If it was possible, it would be a security problem as your JavaScript would have access to personal data belonging to your visitors and stored on other websites.)
If I understand the question - you want to be able to pass a value to a Google search from your page. Rather than accessing the DOM of an external page - you are just trying to enter a value into the search term box on the google page.
All you have to do is append a query string to the Google url (such as "http://www.google.com?query=searchTerm" and it will pass the value to the search box on the google page.
I have slightly modified your code to show this - not how i would normally do it but I wanted to keep your code in place as much as possible so you can see whats going on.
I added a search term input and the onclick event opens the window and submits the query to Google. It could have been done as a form submit as well. Note that I put the JS at the bottom of the page - increases speed of page rendering - not important for this, but good practise movingforward. I also declared the variables together instead of using 2 'var's as well.
your code (slightly modified).
<html>
<head>
</head>
<body>
<form>
<input id="searchTerm" type="text" value="" placeholder="Search term"/>
<button type="button" onclick="getValue()">Search</button>
</form>
<script>
function getValue()
{
var term,myWindow;
term=document.getElementById('searchTerm').value;
myWindow = window.open("http://www.google.com?query="+term,"_self")
}
</script>
</body>
</html>

function variable not passing to global variable

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);

Everytime a page is refreshed i lose data, but i want to keep the last textbox value

i was working on a program that i wrote in php, all is fine, the problem is the html page:
it has 1 textbox and 1 button.
In the textbox i have to write a link
when i load the page it clicks the button automatically, so i can use the php program, then it return back to the html page..
$(document).ready(function(){$('#printbuttoncustomer').trigger('click');});
The links that i need to use are always the same, except the number, example:
http://www.wowhead.com/npc=56843 --- http://www.wowhead.com/npc=56844 etc..
the problem is that everytime the page is loaded, it start to use always the link and can't go on with the next link with the new value
how can i solve this problem?
I think that i could use a txt file to save the last link i used, so in the html i can check the last link in the txt file and set the next value in the textbox.. But don't know how to do.
the code to start is this
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="jquery-2.0.2.js"></script>
</head>
<body>
<form method="POST" action="parser.php">
<input type="text" id="testo" name="testo">
<input type="submit" id="button" >
</form>
<script>
$(document).ready(function(){
$('#button').trigger('click');
});
</script>
</body>
</html>
convert the html page to php. When returning to this page from "parser.php", send back a response with next link and save that in the text field.
You can save the link in a session and not a file :
$_SESSION['URL'] = "Your URL HERE"
next time you read it like this:
var $MyUrl = $_SESSION['URL'];
Please check this link for more on PHP Sessions.
Since you have to persist the information of your last clicked page so that next time you load the page it goes to next page.
You can do this by two ways:-
*Server Side Change:-
You can implement sessions to store the information, where you store the last URL.
*Client Side Change:-
After HTML5 there are a lot of browser storage is available. So you can use local storage, it stores site specific data in browsers persistent memory. Also there is session storage available.Check this page for HTML5 Web Storage.

Categories