I'm making a simple html site with some text and a php-login area. When logged in successfully (which already works) I come to a site where I want the possibility to change paragraph text on the landing page.
I tried this code, but I lets me only change paragraph text on the same site, not on the landing page. Is this possible?
<script type="text/javascript">
function change() {
document.getElementById("name2").innerHTML = "New text inside the text element!";
}
Button to trigger the event
<input id="button1" type="button" value="1" onclick="change()">
well, document refers to the site, not the landing page, right?
besides, if you want to make a change permanent, you should retrieve the text from somewhere you save it in, and not only change what is currently displayed
You could definitely pass a cookie to the Global session variable and you can use an if statement to check on the new page if the session is available and then you can render a new markup.
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
if you set these variable then you can have access to them on each page and can use it to manipulate your data
Related
In one of my php page (Report.php), I am loading its content through jQuery load(). I want to create a "back button" on my php page so that my user can click it to go back pages. Note- I am not looking for browser back button.
Here is my php pages -
report_template.php
//This page query my database and creates a content table<br>
//Table content
Another Report Link
report.php
<button>Go Back</button> //This button will take user to back (equivalent to window.history.back() )
<div id="rept"> </div>
<script>
jQuery('#rept').load('report_template?id=1');
function fetchReport(id){
jQuery('#rept').load('report_template?id='+id);
}
</script>
I am average level skill in jquery/javascript.
At the top of every page start session session_start(); and set the current page as a $_SESSION variable. IE
<?php
session_start();
$_SESSION['last_page'] = $_SERVER['PHP_SELF']; // Or whatever you designate it as
Then you can call it in report.php
<?php
session_start();
<button onClick="window.open(<?= $_SESSION['last_page'] ?>);">Go Back</button> //This button will take user to back (last report page he's seen)
<div id="rept"> </div>
<script>
jQuery('#rept').load('report_template?id=1');
function fetchReport(id){
jQuery('#rept').load('report_template?id='+id);
}
</script>
A slightly simpler, yet less reliable way to do it, is to grab the last page the person was on according to PHP $_SERVER['HTTP_REFERER'] This can also include "off server" pages. Also it may better suit your question if the referrer may, in fact, come from "somewhere else" IE:
<button onClick="window.open(<?= $_SERVER['HTTP_REFERER'] ?>);">Go Back</button>
To put it simply, I tried to make a website where the user can make an element, and then put it in a div element with the id "box". The js script works perfectly fine, and p elements can be created.
And then, I made a php script where it saves the innerHTML of the "box" div and then save it in a .txt file.
Now, the problem is, the script returns the innerHTML value as the original value, before p elements were added in there.
Here's my php script:
<?php
//Basically a function
if(isset($_POST["use_button"]))
{
//Loads the file, which is named test.php
$dom= new DOMDocument();
$dom->loadHTMLfile("test.php");
//Gets the innerhtml value
$div = $dom->getElementById("box")->nodeValue;
//Writes it down in a file.
$file = fopen("stuff.txt","w");
fwrite($file,$div);
fclose($file);
//Just for fast-checking if the code has any errors or not
echo "File saved.";
}
?>
I'd suppose the question is already pretty clear. Which is how to get the CURRENT value instead of the ORIGINAL one.
Here's the entire code if it helps:
<html>
<head>
<script>
//The javascript function to add a "para" into a div with the id "box"
function addstuff() {
var parag = document.createElement("P"); // Create a <button> element
var t = document.createTextNode("Lorem Ipsum"); // Create a text node
parag.appendChild(t);
document.getElementById("box").appendChild(parag);
}
</script>
</head>
<body>
<!--Button to call the funtion-->
<button onclick="addstuff()">Add it</button>
<!--The form for the button to work-->
<form action="" method="post">
<!--The div to put the "para"s in. The style only adds borders-->
<div id="box" style="border: 2px solid black;">
<!--A pre-existing paragraph-->
<p>This was here before</p>
</div>
<!--The button to call the php-->
<input type="submit" name="use_button" value="Store in file" style="width:100%;" />
</form>
<!--The PHP-->
<?php
//Basically a function
if(isset($_POST["use_button"]))
{
//Loads the file, which is named test.php
$dom= new DOMDocument();
$dom->loadHTMLfile("test.php");
//Gets the innerhtml value
$div = $dom->getElementById("box")->nodeValue;
//Writes it down in a file.
$file = fopen("stuff.txt","w");
fwrite($file,$div);
fclose($file);
//Just for fast-checking if the code has any errors or not
echo "File saved.";
}
?>
</body>
</html>
This is not possible:
PHP generates HTML which is then send to the browser.
The browser executes javascript in the page.
There is no PHP in the browser! and server can't know about anything the user does in the browser!!
you can do an AJAX calls with javascript to send data to the server.
Please refer to this answer: https://stackoverflow.com/a/6009208/1275832
You seem to be confused on how <form> element's work. Just adding HTML code to a form client side does not send that HTML code as form data to the server upon form submission. Nor does it automatically update some PHP file.
You would need to add the HTML code to some input control (input, textarea, etc) that is part of the <form>. Then that input's value will be sent to the server on submission at which point you can then use that sent data.
So on the client side you could have a hidden input that will hold the html that is to be sent. Updating it every time you need to change the html
HTML
<form action="" method="post">
<input id="boxinput" type="hidden" name="boxinput"/>
<!--- Rest of form -->
</form>
JS
//cache these so you don't need to call getByElementById every call
var box = document.getElementById("box");
var boxinput = document.getElementById('boxinput');
function addstuff() {
var parag = document.createElement("P");
var t = document.createTextNode("Lorem Ipsum");
parag.appendChild(t);
box.appendChild(parag);
//update the input field
boxinput.value = box.innerHTML;
}
And then on server side, get the input data from the $_POST global and use it as needed
if(isset($_POST["use_button"])) {
$boxHtml = $_POST['boxinput'];
//..
fwrite($file,$boxHtml);
//..
}
Obligatory note: if you are going to be using this saved html in some way, eg echoing it back on some new page, you should sanitize it before saving/using it. Or only showing it in a sandboxed frame (kinda like how Stack Overflow has sandboxed its Stack Snippets)
This is not possible.
But you can handle it manually by using query parameters that are same in php and javascript
Generate your page elements by query parameters.
For example when you got test.php?div=box generate a page that contains a <div id='box'>
There is so many solutions like this
I declare a variable at the beginning of my .js file:
var option="blabla";
On page 1.html I click on a link to page 2.html where I have
<script>document.write(option);</script>
No text is displayed on 2.html. When I refresh the browser while I am on 2.html I get undefined as an output.
What do I have to do to have the text displayed straight after I click the link?
Alternatively, how can I get the following code work to output strUrl on 2.html:
on 1.html I have a link:
<a href="2.html" onclick="function1("item")">
on 2.html I have a div:
<div id="display">document.write(strUrl);</div>
then I have in my .js file:
function1(searchitem)
{
strUrl = 'http://blabla.com/'
+ '?key=' + searchitem;
}
You try to create a Javascript variable on a page and then use it on another page. This is a more-or-less broad problem, since you want to maintain values across pages. First of all, you need to decide where is this value going to be defined and where is it going to be used. If this is more like a server-side variable, then you need to define it on server-side and then generate it into your Javascript code. If you are using PHP, then you can do it like this:
<script type="text/javascript>
var foo = '<?php echo $bar; ?>';
</script>
Naturally, you need to initialize $bar to be able to do that. If the variable should be a client-side variable, then you need to use localStorage, like this on 1.html:
localStorage.setItem("option", "blablabla");
and then load it on 2.html:
localStorage.getItem("option");
Or, if you need to use it both on server-side and client-side, then you can use a cookie for this purpose. Using cookies i slightly more complex, but my answer to another question should get you going.
Let's focus on the cause this did not work for you. A Javascript variable will cease to exist when the page is unloaded, so you will not be able to use its value after that. So, you need to persist it somehow, storing it either on the server or the computer where the browser is being run.
As a side-note, I should mention that you can use Javascript variables accross pages if you load some pages inside iframes of a page, but that is a different scenario.
This is what FORMS and AJAX were invented for. If your server has a PHP processor (virtually ALL of them do), then you can rename your .html files to .php and use a bit of PHP to accomplish your goal.
A web page ending with .PHP works exactly the same as one ending in .html, except that you can now add snippets of PHP code where desired. It is not necessary to have any PHP code, but if you have some it can do stuff.
Method One: FORMs
If you want to switch to page2.html and see a value sent from page1.html, you can use a FORM construct and post the data from page1 to page2:
page1.php
<form action="2.html" method="post">
<input name="option" type="text" />
<input type="submit" name="sub" value="Go" />
</form>
page2.php
<?php
$p1 = $_POST['option'];
?>
<div>On page1 of this website, you typed: <?php echo $p1; ?>. That's what you did.</div>
Note how a <form> uses the name= attribute for the name of the variable that is sent to the other side.
Example Two: The AJAX method
HTML:
<div id=nonForm">
<input id="option" type="text" />
<input type="button" id="myButt" value="Go" />
</div>
<div id="results"></div>
jQuery:
$('#myButt').click(function(){
var opt = $('#option').val();
$.ajax({
type: 'post',
url: 'page2.php',
data: 'option='+opt,
success: function(john){
if (d.length) alert(john); //display result from Page2 in a pop-up box
$('#results').html(john); //Or, display it right on the page
}
});
});
PAGE2.PHP -- The AJAX processor file
<?php
$opt = $_POST['option'];
//Now, you can do something with the data in $opt, and then send back a result
$rtn = 'Hey, you sent: ' .$opt;
echo $rtn;
The primary (and most important) difference between the two methods is that the FORM will change pages on you. The user will be sent from Page1 to Page2, and the screen will flash as this happens.
What's exciting about AJAX is it sends data to Page2, where Page2 can do something with it (for example, a database lookup), and then Page2 sends different data back to Page1. This new data can then be displayed on the page WITHOUT the page refreshing.
Here are a couple of very basic AJAX examples, to get you going:
AJAX request callback using jQuery
I am trying to get the value of a range slider after it moves and then update my page. I have approached this by using "onchange" and calling some javascript to set a value to a text box and using php to get that value. The php does not even grab the value from the text area on load and I am not sure why. It says the id of the input text box is an "unidentified index." There might be a simple thing wrong or I may be approaching it completely wrong. I am new to this...
Here is the code for the slider.
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>
<script>
function printValue(sliderID, textbox) {
var x = document.getElementById(textbox);
var y = document.getElementById(sliderID);
x.value = y.value;
}
window.onload = function() { printValue('slider1', 'rangeValue1')};
</script>
</head>
<body>
<form action='slider.php' method='get'>
<input id="slider1" type="range" min="100" max="500" step="10" onchange="printValue('slider1','rangeValue1')">
<input id="rangeValue1" type="text" size="2">
</form>
<?php
echo $_GET['#rangeValue1'];
?>
</body>
</html>
The js function does set input text box, but the php script doesn't happen. I need to get the value in PHP because the page I'm including it in is written in PHP. I don't know if, or how, the page has to be reloaded. I tried using location.reload() in the onchange function and it just continuously loaded the page.. Please help! Any input will be helpful! Thanks!
It looks like you might be getting Javascript and PHP mixed up.
PHP is run solely on your server when a browser accesses a php file. The output of the php file (like when you use echo) is sent as a webpage. However, Javascript is run solely in the browser. To make them communicate, you will need to load another webpage (or reload the current webpage). You can either use a form or directly craft the URL (probably easier in this case).
So you could do something like this inside printValue():
location.querystring="?value=" + x.value;
This will create a GET argument, which you can access with $_GET['value'], and reload the page.
EDIT: Performance Warning!
Every time the slider is moved, your server will end up resending the webpage, which could slow down the server. You might want to only send the new value after the user has clicked a button or something, in which case it would be easier to use a form.
I have two html pages one is parent.htm and other is child.html where i have given href in parent.htm' tochild.html, here i have to access the elements ofparent.htminchild.html`, here are my two files
parent.htm
<!DOCTYPE html>
<html>
<body>
<form>
<input id=text1 type=text name="test2">
Open kid
</form>
</body>
</html>
child.html
<html>
<script type="text/javascript">
function parent(){
//here i want to access values from parent.htm page, but does not work
var value = parent.getElementById('text1').value;
var value2=top.getElementById('text1').value;
alert(value);
}
</script>
<body onload="parent()">
<form>
</form>
</body>
</html>
Thanks in advance
Probably the easiest way to do what you want is through a cookie. It's a small text file stored on the client that can persist values across pages. If you don't specify an expiration date, the cookie will expire when the user closes their browser.
Cookie tutorial
Edit
Something else you could do is use Javascript to submit the form by clicking on the link. I think it's formname.submit() - which would allow you to read the values out of the form post. (Though it would be a little more work than just reading the cookie)
If you're only passing one or two fields I'd use the cookie. More than that you may want to consider submitting the form through Javascript.
First change the following:-
Open kid
to :-
Open kid
target="_self" means that the child page will open in the same parent window, effectively destroying the parent and its code.
Afterwards, access the parent's form textbox element with:-
var parentTextBox = window.opener.document.getElementById('text1');
I think you cannot do that, at least the way you are trying.
Once you clicked on "Open kid", your current page will be replaced by the new one, so you can't access that attribute.
You should be able to get around this by using cookies, passing the needed values in the url or with Web Storage.
You should be able to user window.opener to grab a reference to the parent window.
var parent = window.opener
I see -- you cannot access DOM elements from a previous page via javascript (AFAIK).
This is traditionally handled with HTTP post variables, passing the form variables collection to the subsequent page via some back-end procedures.
Or (as Moje notes) open the page in a new window so you can access the parent with window.opener
parent.htm
<!DOCTYPE html>
<html>
<body>
<form method="GET" id="myform" action="child.html">
<input id=text1 type=text name="test2">
Open kid
</form>
</body>
</html>
child.html
<!DOCTYPE html>
<html>
<body onload="alert(window.location.toString().split('?')[1].split('=')[1])">
</body>
</html>
Might contain some typo, but the idea is to submit form by GET to the child and then read GET parameters from window.location after child.html is loaded.