Document.write on a different html page - javascript

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)

Related

Pass Javascript variable to another page via PHP Post

I am having two php pages:
page 1:
<form class="form-horizontal" role="form" method="post" action="Page2.php">
<button id="place-order" class="btn btn-lg btn-success">Place Order</button>
<div id="ajax-loader" style="display:none;"><img src="images/ajax-loader.gif" /></div>
</form>
<script>
var id = Math.random();
$(document).ready(function() {
$('#place-order').on('click', function() {
$(this).hide();
$('#ajax-loader').show();
});
});
</script>
As on form, it redirects to Page2.php, I want to pass the Javascript variable "id" from Page1 to receive it in Page2.
I have tried using cookies, but need an alternative approach.
I am not understanding the transistion from PHP to JS and vice-versa. Help is appreciated.
Thanks in advance
Dear you can do it very easily with ajax. Ajax has data attribute which helps you pass your data from javascript to another page.
This link will help you a lot
https://api.jquery.com/jquery.ajax/
You can use session storage or cookies.
Example for session storage:
// First web page:
sessionStorage.setItem("myVariable", "myValue");
// Second web page:
var favoriteMovie = sessionStorage.getItem('myVariable');
You could use a query string to pass the value to the next page.
Add an ID to the form
<form class="form-horizontal" role="form" method="post" action="Page2.php" id="order-form">
Update the action of the form to add this query string from our JS variable
var id = Math.random();
$('#order-form').attr('action', 'Page2.php?id=' + id);
Get this variable in PHP (obviously you might wanna do more checks on it)
<? $id = $_GET['id'] ?>
We can now use $id anywhere in our PHP and we'll be using the ID generated from JS. Neat, right? What if we want it in JS again though? Simply add another script tag and echo it there!
<script type="text/javascript">
var id = <? echo $id ?>;
</script>
EDIT: Updated to add a little about how it works as you said you're not too sure about the transition between PHP and JS.
PHP runs on the server. It doesn't know much about the browser, and certainly doesn't know about JS. It runs everything and finishes executing before the web page is displayed. We can pass PHP variables to JS by creating script tags and creating a new javascript variable, echoing the PHP value.
JS (JavaScript) runs in the browser. It doesn't know about anything that happens on the server; all it knows about is the HTML file it is running in (hit CTRL+U to see raw HTML). As JS runs at a completely separate time to PHP there is no easy way to transfer variables (e.g. $phpVar = myJSVar). So, we have to use server methods like POST or GET.
We can create a GET or POST request in 2 main ways:
Using a form
Using an AJAX request
Forms work in the way I've outlined, or you can create a hidden field, set the value you want and then check for that. This involves redirecting to another page.
AJAX (Asynchronous Javascript And Xml) works slightly differently in that the user doesn't have to leave the page for the request to take place. I'll leave it to you to research how to actually program it (jQuery has a nice easy API for it!), but it basically works as a background request - an example would be displaying a loading spinner whilst loading order details from another page.
Hope this helps, let me know if something's not clear!

Getting values from html form as JavaScript variables

i want to capture input variables sent via form from one page to another.html page and obtain these values as JavaScript variables. Can this be done.
This is my form;
<form action='another.html' id='form' data-ajax='false'>
<input id='sent_by' value='tom'/>
<input type='submit' value='Submit'/>
</form>
And in my another.html i tried to get the values as;
var sent_by = $.session.get("sent_by");
But i am not able to get the values. All help is appreciated.
You can use the browser's localStorage to achieve this. Before submitting and going to the other page store all the values of the form in the localStorage and you can access it on the other page:
Page1.html
Field Name = "name" <input type="text" name="name" id="name" />
Read the value and store it to localStorage
localStorage.setItem('name', document.getElementById('name').value);
and so on.
You can make a function in JavaScript that saves all the fields of the form in localStorage on / before submit.
To read these values on the other page:
Page2.html
Value stored for key name can be get using the following JavaScript:
localStorage.getItem("name");
NOTE
the page1.html and page2.html should be in the same domain for you to access the localStorage.
Read more about localstorage at https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage
Have you tried using Window.localStorage? It's similar to sessionStorage but with no expiration date. So, be sure to clear it once the browsing session ends.
I think the answer provided by #Shakti Phartiyal is probably the most practical and a sweet trick I might add. The main reason I'm writing this post is because I had also taken a long path of using javascript to pass along this kind of information. It resulted in me bewildered at how powerful PHP can be for some tasks that you dedicated javascript to do. (Yea I know some javascript wizards out there can do everything with it, I'm just talking about basic programming tho). So if you wondered what the PHP way of passing this around:
Your modified html form:
<form action='another.html' id='form' data-ajax='false' method='post'>
<input id='sent_by' value='tom' name='uname'/>
<input type='submit' value='Submit'/>
</form>
and then in "another.php" you would have this to retrieve the input from the form:
<?php
$uname= htmlspecialchars($_POST['uname'];
?>
Great. But how to make this php variable into javascript?
Ah, the fun part. You're going to write javascript to your webpage with php - you do something like this:
var uname = "<?php echo $uname; ?>";

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>

Sending form data to HTML Page and Retrieving it with Javascript without any PHP/Python

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

Categories