I have looked around for answers to this question but either do not understand the logic of the other answer, or have done something wrong trying to incorporate those answers.
I have 2 pages of HTML, where the first page has this form
<form class='registerbutton' action='registration.php' method = "POST">
<input type='email' name='email' placeholder='Email'>
<input type='submit' value='Register'>
<script> localStorage.setItem("useremail",email);</script>
</form>
When I do not use the method="POST" I can see in the URL that the email value is added onto the URL and therefore that this form works. However, in my next page I have this:
<body>
<script>
var test = LocalStorage.getItem("useremail");
document.write(test);
</script>
</body>
However, this does not work. I have also tried <?php echo email;?> but that also does not work. I am sorry if this is a trivial question. I am more used to other programming languages and am new to web development.
This solution will work client side only. Try it should work fine, it should work fine. If any thing else then let me know.
Page 1
<form class='registerbutton' action='registration.php' method="POST">
<input type='email' name='email' placeholder='Email' id="emailId">
<input type='submit' value='Register'>
</form>
<script type="text/javascript">
var email = document.getElementById('emailId');
email.addEventListener("keyup", function(event) {
localStorage.setItem('useremail', event.target.value);
});
</script>
Page 2
<body>
<script type="text/javascript">
var test = localStorage.getItem("useremail");
document.write(test);
</script>
</body>
SERVER SIDE
<?php
echo $_POST['email']; // In case of post and $_REQUEST['email'] will work for both.
?>
Since your method is POST, so you can access your email with PHP by the following:
<?php echo $_POST['email']; ?>
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am making a website using javascript and php.
When the user logout from the website and then if he clicks the back button of browser then it goes to the previous state in which the user is logged in.
1. How can I restrict this?
2. Can it be done by sessions, or anything else?
Use sessions
Login.php:
...
$_SESSION["foo"] = $foo;
...
Logout.php:
...
unset($_SESSION["foo"]);
...
In login.php you will set the SESSIONvariable named foo (so the user is logged on). When he logs out, you will destroy/unset the SESSIONvariable named foo, so in each logged in page you may want to do a if statement checking if the SESSION variable is set(logged in) else (not logged in) then you can redirect the user to where ever you want it to.
When user clicks back button the content is loaded from the browser cache and not from the server. That is why the it happens.
From my understanding, if the previous page processes some input from the same page, the browser shows an webpage expired notification.
Here is my example in php.
login.html
<!doctype HTML>
<html>
<body>
<form action="action.php" method="post">
username <input type="text" name="uname"/>
<input type="submit" value='login' />
</form>
</body>
</html>
action.php
<?php
if(isset($_POST["uname"])){
$user = $_POST["uname"];
session_start();
echo "welcome ". $user;
}
if(isset($_POST["logout"])){
session_unset();
}
?>
<html>
<body>
<form action="action.php" method="post" >
<input type="hidden" name="logout" />
<input type="submit" value="logout" />
</form>
</body>
</html>
If user clicks backbutton after loging out browser shows webpage expired message.
I hope you have good with nice pleasure.
Please check this code may be help you.
File name: _32_session.php
<?php
session_start();
?>
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label>Please enter your Name</label>
<input type="text" name="name">
<input type="submit" name="submit" value="Login">
<input type="submit" name="Unset" value="Logout">
</form>
</body>
<?php
if(isset($_POST['Unset']))
{
session_destroy();
header('Location:_32_session.php');
}
elseif(isset($_POST['submit']))
{
$name = $_POST['name'];
$_SESSION['name']=$name;
}
if(isset($_SESSION['name']))
{
echo "<br>";
echo "Wellcome ".$_SESSION['name'];
}
else
{
echo "<br>";
echo "Wellcome Guest";
}
?>
</html>
Use this code and check.
Regards,
I've been trying to integrate ckeditor in my php website, and I've encountered the following issue.
Essentially, the content in ckeditor wouldn't appear in the $_POST variable after submitting the form.
I looked the issue up and apparently one has to update the form field with a small piece of code.
So I wrote the corresponding script and linked it to the submit button in order to get the result I want, but $_POST still shows up as empty.
I'm inexperienced with Javascript so the error probably lies there. Any ideas?
cktest.php:
<!DOCTYPE html>
<html>
<head>
<title>A Simple Page with CKEditor</title>
<!-- Make sure the path to CKEditor is correct. -->
<script src="http://localhost/ECLIPSEPHP/ckeditor/ckeditor.js"></script>
</head>
<body>
<form action = <?php echo $_SERVER['PHP_SELF']
?>>
<textarea name="test" id="test" rows="10" cols="80">
This is my textarea to be replaced with CKEditor.
</textarea>
<input type = "submit" name = 'submitButton' id = 'submitButton' value = 'Submit'>
<script>
// Replace the <textarea id="test"> with a CKEditor
// instance, using default configuration.
CKEDITOR.replace( 'test' );
</script>
<script type = "text/javascript" src = "http://localhost/ECLIPSEPHP/js/update.js"></script>
</form>
</body>
</html>
<?php
var_dump($_POST);
//echo $_POST['test'];
?>
The javascript supposed to handle the onclick event :
function updateAllMessageForms()
{
for (instance in CKEDITOR.instances) {
CKEDITOR.instances[instance].updateElement();
}
}
var submitButton = document.getElementById('submitButton');
submitButton.onclick = updateAllMessageForms;
There are quite a lot of problems with that code. The first thing to check is to add a method to that form tag: method="post".
See what <form action = <?php echo $_SERVER['PHP_SELF'] ?>> renders. It looks like it could be a wrong. I'm guessing it should be more like <form action="<?php echo $_SERVER['PHP_SELF'] ?>">.
Don't use ' for HTML attribute delimiters, use " instead: 'submitButton' --> "submitButton".
If you edit the updateElement a little: CKEDITOR.instances[instance].updateElement(); alert(1); - do you see the alert? If not, that code is not being called and you need to edit it so that it is.
Don't add spaces between your attribute name, the equals symbol and the value. That looks very strange and could be interpreted wrong or it could send Internet Explorer into quirks mode. Try to change this style: type = "submit" to type="submit" and keep up with that style.
Remember that it's often a good idea to look at the Rendered source in the browser to see what the browser actually gets. Happy coding!
I am printing a very simple JavaScript using PHP, which doesn't get executed. If I print the data, I see the following script (exactly as needed) at the end of the HTML file:
<script type="text/javascript">
document.getElementById("message").innerText="Email already exists";
</script>
I have also tried using innerHTML="Email already exists";.
This is printed in PHP as such:
echo "<script type=\"text/javascript\">
document.getElementById(\"message\").innerText=\"Email already exists\";
</script> ";
In my HTML I have an element which has the ID: message. It looks like this:
<h3 id="message"> </h3>
What I am expecting is to get "Email already exists" in the h3, however this doesn't happen. The JavaScript is not executed. If I use the exact same JavaScript code but place it ahead or on an "onclick" request, the code works.
One thing which could be relevant: I noticed that the JavaScript is printed after the closing HTML tag.
How do i get the JavaScript code to execute after being echo'ed into the HTML? I've read several threads which said its supposed to simply run, however mine doesn't. I have tried about 50 different fixes, none of which worked.
The code: http://ideone.com/dmR42O
You mentioned this:
One thing which could be relevant. I noticed that the javascript is
printed AFTER the closing html tag (the ).
That is very relevant. Any Javascript must be contained within the <html> element (before </html>). But, be sure that the Javascript appears after the <h3>. Javascript will run when it's encountered, as Marc said in a comment above.
If the Javascript must be before the , then do this:
window.onload=function(){
document.getElementById("message").innerText="Email already exists";
};
Try it like this:
echo '<h3 id="message"> Email already exists!</h3>';
<!DOCTYPE html>
<html>
<body>
<form id="submitform" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="logIn_email_input" name="email" type="text" placeholder="Enter e-mail address" autocomplete="off">
<input id="logIn_password_input" name="password" type="password" placeholder="Enter password" autocomplete="off">
<input id="logIn_submit" type="submit" name="logIn_submit">SIGN UP</button>
</form>
<?php
$query = mysql_query("SELECT userid FROM users WHERE email = '". $email ."'");
if (mysql_num_rows($query) > 0) {
echo '<h3 id="message"> Email already exists!</h3>';
}
?>
<body>
</html>
You had a lot of issue here (maybe typos ?)
action="<?php echo $PHP_SELF;?>" should be action="<?php echo $_SERVER['PHP_SELF']; ?>"
<button id="logIn_submit" should be <input id="logIn_submit" type="submit" name="logIn_submit">
<? php had extra space should be <?php
If statement was missing closing brace }
No <body> tags
I need to redirect one page to another page using the form value.
I have this code, which i think is fine for first page and what should i put in the other page where i want to show the data ??
<meta http-equiv='refresh' content='0;url=http://site.com/page.php'>
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php echo $url; ?>">
<script language="JavaScript">document.myform.submit();</script>
</form>
Regards
You can't mix a meta-refresh redirect with a form submission per se.
Also, meta-refreshes are terrible anyway. Since you are already in control of the receiving page, and it's using PHP, use that to accomplish the redirect. Try this:
<form action="http://site.com/page.php" method="post" name="myform">
<input type="submit" value="Go!" />
</form>
Then, in page.php:
<?php
// Act on the input, store it in the database or whatever. Then do the redirect using an HTTP 302.
header('Location: http://example.com');
?>
If you need the form to pass the destination along to page.php, you'll want to sanitize it to prevent a LOT of security problems. Here's a rough outline.
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="destination" value="http://example.com" />
<input type="submit" value="Go!" />
</form>
Then, in page.php (copied re-encoding from answer https://stackoverflow.com/a/5085981/198299):
<?php
$destination = $_POST['destination'];
$url_parsed = parse_url($destination);
$qry_parsed = array();
parse_str($url_parsed['query'], $qry_parsed);
// Check that $destination isn't completely open - read https://www.owasp.org/index.php/Open_redirect
$query = parse_url($destination);
$destination = "{$url_parsed['scheme']}{$url_parsed['host']}{$url_parsed['path']}?" . http_build_query($query);
header('Location: ' . $destination);
?>
I haven't double-checked that code (just wrote it here in the browser), but it should suffice as a rough sketch.
in site.com/page.php
<script>window.location.href = 'newPage.php';</script>
You will have to write this outside the php tags though.
To redirect a page in PHP, use:
<?php
header('Location: url/file.php');
?>
To refresh to a different page in HTML, use:
<meta http-equiv='refresh' content='0;url=http://url/file.php'>
In the content attribute, 0 is the amount of seconds to wait.
To refresh to a different page in JavaScript, use:
window.location.href = 'url/file.php';
When none of these work, follow an anchor link, using HTML:
Click here to go now!
To answer your question, it can be done several ways:
1) Very bad, requires two files, super redundant
HTML file:
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php=$url?>">
</form>
<script type="text/javascript">
// Submit the form
document.forms['myform'].submit();
</script>
Page.php:
<?php
// Catch url's value, and send a header to redirect
header('Location: '.$_POST['url']);
?>
2) Slightly better, still not recommended
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php=$url?>">
</form>
<script type="text/javascript">
// Set form's action to that of the input's value
document.forms['myform'].action = document.forms['myform'].elements['url'].value;
// Submit the form
document.forms['myform'].submit();
</script>
3) Still very redundant, but we're getting better
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php=$url?>">
</form>
<script type="text/javascript">
// Simply refresh the page to that of input's value using JS
window.location.href = document.forms['myform'].elements['url'].value;
</script>
4) Much better, save yourself a lot of trouble and just use JS in the first place
<?php
// Start with a PHP refresh
$url = 'url/file.php'; // Variable for our URL
header('Location: '.$url); // Must be done before ANY echo or content output
?>
<!-- fallback to JS refresh -->
<script type="text/javascript">
// Directly tell JS what url to refresh to, instead of going through the trouble to get it from an input
window.location.href = "<?php=$url?>";
</script>
<!-- meta refresh fallback, incase of no JS -->
<meta http-equiv="refresh" content="0;url=<?php=$url?>">
<!-- fallback if both fail (very rare), just have the user click an anchor link -->
<div>You will be redirected in a moment, or you may redirect right away.</div>
Save that with a .php extension, and you should be good to go.
I am new to JavaScript and didn't arrive to find a working script that does the following:
I have a hidden form in JavaScript that should be submitted on an onclick event. The fields in the form are used in the target PHP file to create output. The target PHP file should be loaded inside a div on the current page without reloading the whole page.
The problem is that I cannot get the target PHP file to load inside the div on the current page, but the target PHP page is simply loaded showing the results that I want to have inside the div.
Any help would be very appreciated!
Update #1
I did a YouTube tutorial on jQuery ajax request where the result is shown in a div on the same page. I double checked the code many times and it looks the same as in the tutorial. In the tutorial the code is working but for me it isn't. Below are all the files I'm using and the code.
ajax.html:
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
//
$(document).ready(function(){
$("#button").click(function(){
var sendu = $("#username").val();
var sendp = $("#password").val();
$.ajax({
type="POST",
url: "ajax.php",
data: "username="+sendu+"&password="+sendp,
dataType: "json",
success: function(msg,string,jqXHR){
$("#result").html(msg.name+"<br />"+msg.password);
}
});
});
});
</script>
</head>
<body>
Name:<input type="text" id="username" name="username" /><br />
Password:<input type="password" id="password" name="password" /><p>
<input type="button" id="button" value="submit" />
<p><div id="result"></div>
</body>
</html>
jquery.js from this url:
http://code.jquery.com/jquery-1.6.2.min.js
ajax.php:
<?
$name = $_REQUEST['username'];
$password = $_REQUEST['password'];
$list = array('name'=>$name, 'password'=>$password);
$c = json_encode($list);
echo $c;
?>
I'm using the WAMP server as my localhost, could it have anything to do with a setting?
Since you provided no code, I'll have to guess, either:
1) You have the AJAX code to load the php response into a division but the page still refreshes, in which case - when the form is submitted you need to prevent the default event triggering, do this with:
event.preventDefault();
Stick that as the first thing inside the function that get's executed inside the onClick(). It should all work now. Incidentally, you probably want onSubmit() instead, in case someone hits 'Enter' instead of clicking the 'submit' button (although I'm not sure if it's part of the standard javascript/DOM). Check out a javascript library called JQuery, it makes javascript a breeze.
2) You actually want AJAX, in which case go to jquery.com, download their javascript library and go through some tutorials on ajax requests. The basics are something like:
$("#id_of_your_form").submit(function(event){
event.preventDefault();
$.post( url_of_php_file, $("#id_of_your_form").serialize(), function(data){
$("#id_of_your_div").html(data);
});
});
This code is basic, but should work, provided you remember to include the library file in your .html file.
#UPDATED
Is there any particular reason you're using the JSON object? I just haven't used it before myself, so my input here might be limited. Try this:
ajax.html
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
//
$(document).ready(function(){
$("#button").click(function(event){ //don't forget to pass the event as an argument
//need this, or your page will follow the url defined in the form
event.preventDefault();
var sendu = $("#username").val();
var sendp = $("#password").val();
$.ajax({
type: "POST",
url: "ajax.php",
data: "username="+sendu+"&password="+sendp, /*shouldn't the method be GET then?*/
dataType: "json",
success: function(msg){
$("#result").html(msg.name+'<br />'+msg.password);
}
});
});
});
</script>
</head>
<body>
<form action="miss.php" method="post">
Name:<input type="text" id="username" name="username" /><br />
Password:<input type="password" id="password" name="password" /><p>
<input type="submit" id="button" />
</form>
<p><div id="result"></div>
</body>
</html>
ajax.php
<?
$name = $_POST['username']; //use $_POST array instead
$password = $_POST['password'];
$list = array('name'=>$name, 'password'=>$password);
$c = json_encode($list);
echo $c;
?>
(Note: I haven't checked the php code as such, since as I said, I'm not too familiar with JSON objects)
If you don't specifically need the json object, you could try using standard text/xml for simplicity. Also, consider using $.post instead of $.ajax, it should make things easier.
Also, don't forget to use the form tags around your input or your html won't be valid(citation needed) and finally, if you're working with html in your javascript it might be a good idea to use single quotes instead of double quotes to indicate your strings. Hope that helped.
#UPDATE 2
Okay, since you don't need JSON for basic stuff(leave JSON for later), use text/xml instead. Also, have a look at the comments. This should all work, provided WAMP is running and both files are in the same folder. Here's the code:
ajax.html
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
//
$(document).ready(function(){
$("#login_form").submit(function(event){ //don't forget to pass the event as an argument
//need this, or your page will follow the url defined in the form
event.preventDefault();
var sendu = $("#username").val();
var sendp = $("#password").val();
$.post("ajax.php", {'username' : sendu, 'password' : sendp}, function(data){
$("#result").html(data); //data is everything you 'echo' on php side
});
});
});
</script>
</head>
<body>
<form action="miss.php" method="post" id="login_form">
Name:<input type="text" id="username" name="username" /><br />
Password:<input type="password" id="password" name="password" /><p>
<input type="submit" id="button" />
</form>
<p><div id="result"></div>
</body>
</html>
ajax.php
<?php
//you used shorthand <? as the php tag, it's probably why your code didn't work
//I would discourage using the shorthand, it's silly
$name = $_POST['username']; //use $_POST array instead
$password = $_POST['password'];
echo $name.'<br />'.$password;
?>
If this doesn't work...check if you have skype running, for some reason WAMP will not work with skype on at the same time, it's weird.
You can use Ajax. The run of the mill Ajax will let you refresh parts of the page w/out reloading the page, which in your case is submit the form and load the target on the current page. I will suggest you to start with jQuery.
the problem is the form is still submitting, when i do what your trying to do, i do it slightly different. try this
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
function gO(frM){
$.ajax({
type:"POST",
url: "ajax.php",
data: frM.serialize(),
dataType: "json",
success: function(msg,string,jqXHR){
$("#result").html(msg.name+"<br />"+msg.password);
}
});
}
</script>
</head>
<body>
<form action="" onsubmit="javascript:gO(this);return false;">
Name:<input type="text" id="username" name="username" /><br />
Password:<input type="password" id="password" name="password" /><p>
<input type="button" id="button" value="submit" />
</form>
<p><div id="result"></div>
</body>
</html>