I have done a conditional redirect with javascript (depending of referer). However now I need to detect if user got redirected and then he clicked back button and got again to the page he has been redirected from. In this case I need no to redirect him again.
I have found a solution here - but I am failed to combine php and javascript properly, so there is always an error - How do I detect if a user has got to a page using the back button?
Code:
<form name="ignore_me">
<input type="hidden" id="page_is_dirty" name="page_is_dirty" value="0" />
</form>
<script language="javascript" type="text/javascript">
var dirty_bit = document.getElementById('page_is_dirty');
if (dirty_bit.value == '1') {
document.write("<p>Do Not Redirect</p>");
}
else {
<?php if((stristr($_SERVER['HTTP_REFERER'],"thoughts") != FALSE) { ?>
<?php $setupform = '<form id="form1" method="post" action="http://yahoo.com">'; ?>
<?php $submitform = 'document.getElementById(\'form1\').submit(); </form>'; ?>
<?php echo $setupform; ?>
<?php echo $submitform; ?>
<?php } ?>
}
function mark_page_dirty() {
dirty_bit.value = '1';
}
</script>
What is wrong here?
The error is that it simply doesn't redirect - it gives a blank page with code on it:
<form name="ignore_me">
<input type="hidden" id="page_is_dirty" name="page_is_dirty" value="0" />
</form>
<script language="javascript" type="text/javascript">
var dirty_bit = document.getElementById('page_is_dirty');
if (dirty_bit.value == '1') {
document.write("<p>My First JavaScript</p>");
}
else {
<form id="form1" method="post" action="http://yahoo.com">document.getElementById('form1').submit(); </form>
}
function mark_page_dirty() {
dirty_bit.value = '1';
}
I took a look at your code and here are some points:
When mixing PHP and JS, remember, that PHP code will be executed first, it will not read any of JS statements
You put a block of PHP code into if statement of JS.
Here is a possible solution for you:
PHP logic first:
$redir = false ;
if((stristr($_SERVER['HTTP_REFERER'],"thoughts"))) {
$redir = true ;
}
HTML form:
<form id="check" action="a.php" method="post">
<input type="hidden" name="durty_bit" value="1" />
</form>
JS check:
var check = getElementById("check") ;
if (check && check.durty_bit == 1){
document.write("<p>Do Not Redirect</p>");
} else {
<?php if ($redir){ ?>
document.write('<form id="form1" method="post" action="http://yahoo.com"> </form>');
document.getElementById("form1").submit() ;
<?php } ?>
}
Related
I'm pretty new with PHP, so help please.
I need a web page in php with a checkbox. That page should refresh itself each time I do an action to the checkbox (so for both check or uncheck). Once it’s refreshed the page should keep the latest value of the checkbox.
I tried the following example modifying another code I took from StackOverflow, but it doesn’t works as I wish.
Any suggestion?
<?php
session_start();
$checked = "";
if($_SESSION['myaction'] != $_SESSION['value'])
{
if(isset($_POST['sharks']))
{
$_SESSION['value'] = $_POST['sharks'];
}
else
{
$_SESSION['value'] = '';
echo ":(";
}
$_SESSION['myaction'] = $_SESSION['value'];
}
?>
<form action="" method="POST">
<?php
print '<input name="sharks" type="checkbox" value="1" id="sharks" ';
if ($_SESSION['value'] == 1)
{
echo "checked='checked'";
}
$myaction = 2;
print ">";
?>
</form>
<form method='POST'>
<input name='sharks' type='checkbox' value='1' id='sharks' />
</form>
Some simpple, vanilla, Javascript that makes use of the localStorage ( or sessionStorage ). The click handler will set the checked status and on page load that value will help re-check, or not, the checkbox. Javascript is intended for this sort of purpose - though it is entirely possible to use PHP to re-check the checkbox when the page reloads provided it has some means to check a value against a stored value or a form submission.
document.addEventListener('DOMContentLoaded',()=>{
let chk=document.querySelector('input[type="checkbox"][name="sharks"]');
chk.checked=localStorage.getItem( chk.name )==null || localStorage.getItem( chk.name )=='false' ? false : true;
chk.addEventListener('click',e=>{
localStorage.setItem( chk.name, chk.checked )
location.reload();
});
});
Don't use a checkbox if you don't want the behaviour of a checkbox.
If you are submitting data, use a submit button. Users expect submit buttons to trigger a reload of the page.
<?php
$current_state = get_state_from_database_or_session_or_whatever();
if (isset($_POST['new_state'])) {
if ($_POST['new_state']) == "on") {
$current_state = "off";
} else {
$current_state = "on";
}
update_datebase_or_session_or_whatever_with_new_state($current_state);
}
$other_state = "off";
if ($current_state == "off") {
$other_state = "on";
}
?>
<p>The current state is <?php echo $current_state; ?></p>
<form method="post">
<button name="state" value="<?php echo $other_state; ?>">Set state to <?php echo $other_state; ?></button>
</form>
What you need to is pretty simple- assuming you are submitting the form on the same page.
<?php
$filterUsers=array();
if(isset($_GET['users'])){
foreach($_GET['users'] as $key){
$filterUsers[]=$key;
}
function valueInFilter($value){
if(in_array($value, $filterUsers)){
echo "checked";
}else{
echo "";
}
}
?>
<html>
<head>Filter </head>
<body>
<form method="get" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<input type="checkbox" name="users[]" value="john" id="1" <?php
valueInFilter("john",$filterUsers) ?>>
<label for="1"> John doe</label><br>
<input type="checkbox" name="users[]" value="john" id="2" <?php
valueInFilter("mayor",$filterUsers) ?>>
<label for="2"> John Mayor</label><br>
</form>
</body>
</html>
This is not an job for PHP like Professor Abronsius wrote.
Write it in JavaScript like this:
(() => {
// on page reloaded
const checkboxNode = document.getElementById('sharks')
if (localStorage.getItem('sharkCheckBox')) {
// the checkbox is stored as CHECKED
// e.g. check the checkbox again or what ever:
checkboxNode.checked = true
} else {
// the checkbox is stored as NOT checked
}
// handle the click
checkboxNode.addEventListener('click', function() {
// get the checkbox status
const isChecked = this.checked
// store the checked status inside the browser cache
localStorage.setItem('sharkCheckBox', isChecked)
// there are several ways to to an page reload. Here an example
// see details here https://stackoverflow.com/a/39571605/7993505
location.reload()
})
})()
I'm trying to make this work but there something wrong:
<?php
if(isset($_POST['submit'])){
echo "<script>location='https://google.com'</script>";
exit();
}
?>
<html>
<head>
<script>
function onSubmit() {
document.getElementById('menu_post').value = 'main';
document.forms['MenuForm'].submit();
}
</script>
</head>
<body>
<a onclick="onSubmit();return false;" href="javascript:void(0)">Test</a>
<form name="MenuForm" method="post" action="index.php">
<input type="hidden" id="menu_post" name="menu_post" value="" />
</form>
</body>
</html>
I tried this one [php on submit redirect to another page
But still doesn't work.
Thanks in advance for any help guys.
It should be something like:
if(isset($_POST['submit'])){
echo "<script>window.location.href='https://google.com'</script>";
exit();
}
Edit
You've actually nothing being posted as 'submit'.
if(isset($_POST['menu_post'])){
echo "<script>window.location.href='https://google.com'</script>";
exit();
}
So I want to replace the form submission with a thank you message after you submit, I need the PHP because this will eventually deal with databases in that php, however right now... The only way it works, is that is Type in a name, press submit. It goes back to a blank form, enter nothing (nothing in address) and submit again and it works...
right now the only way i could think of making it work would be some dummy checkbox where when checked value changes the post is sent. However i don't think that will pass with my groupmates
wondering how i can make it only have to submit once.
Index.PHP
<!DOCTYPE HTML>
<html>
<head>
<?php include_once "thankyou.php"; ?>
<script type="text/javascript" src="jquery-3.1.0.js"></script>
<script type="text/javascript">
$("document").ready(function() {
$("#ContactUs_Submit").click(function(evt) {
<?php $inputName = $_POST["ContactUs_Name"]; ?>
$("#ContactUs_CommentsDiv").replaceWith("<?php
thankyou($inputName); ?>");
return false;
});
});
</script>
</head>
<body>
<div id="ContactUs_CommentsDiv">
<form method="post">
<!-- WITH JQUERY USE SINGLE URL, WITH PAGES-->
<label for="ContactUs_Name">Name: </label>
<input type="text" name="ContactUs_Name" id="ContactUs_Name" />
<br/>
<Label for="ContactUs_Email">Email: </Label>
<input type="email" name="ContactUs_Email" id="ContactUs_Email" />
<br/>
<input id="ContactUs_Submit" type="submit">
</form>
</div>
</body>
</html>
thankyou.php
<?php
function thankyou($name) {
echo "<p> Thank you for your input ";
//if ($_POST["ContactUs_Name"] != "") {
// echo " " . $_POST["ContactUs_Name"];
// }
if ($name != ""){
echo $name;
}
echo "!";
}
?>
Can you not just use AJAX to do this?
I want to learn how to keep value after a post request.
In my code, I have these variables:
myvar
myans
result
myvar is a random val between 0-5. I will get myans from my input if myans == myvar, then result will be true (else it will be false).
I see myvar before I submit my ans just for trying, but although I see the var when I send it, what I see it is sometimes false and sometimes true. What am I missing?
example.php:
<?php
session_start();
if (!isset($_COOKIE['result'])) {
setcookie("result","EMPTY");
}
setcookie("myvar",rand(0,5));
if (!empty($_POST)) {
if ($_POST['myans'] == $_COOKIE['myvar']) {
setcookie("result","TRUE");
}
else {
setcookie("result","FALSE");
}
}
?>
<html>
<head>
<title>Example</title>
</head>
<body>
<form method="post" action="">
<?php echo $_COOKIE['myvar'] ?>
<input type="text" name="myans">
<input type="submit" value="Send">
<?php echo $_COOKIE['result'] ?>
</form>
</body>
</html>
The problem you were having was caused by your random number generator making creating a new number before comparing to the original. I made some changes to only set "myvar" if it's empty. this will only set it once, but at least you can see your code working as intended. I recommend you plan out what exactly what functionality you want before adding to it.
I also switched you out from the "$_COOKIE" var to "$_SESSION" vars. They are hidden from the client, and by php default last about 24 minutes if not refreshed. I don't know what you plan on using this for, but using cookies allows the end user to manipulate that info. If this is not a concern for you, by all means just uncomment the "setcookie()" lines.
<?php
session_start();
if (!isset($_SESSION['result'])) {
//setcookie("result","EMPTY");
$_SESSION["result"] = "EMPTY";
}
//setcookie("myvar",rand(0,5));
if(empty($_SESSION["myvar"])){
$_SESSION["myvar"] = rand(0,5);
}
//
if (!empty($_POST)) {
if ($_POST['myans'] == $_SESSION['myvar']) {
//setcookie("result","TRUE");
$_SESSION["result"] = "TRUE";
} else {
//setcookie("result","FALSE");
$_SESSION["result"] = "FALSE";
}
}
?>
<html>
<head>
<title>Example</title>
</head>
<body>
<form method="post" action="">
<?php echo isset($_SESSION['myvar']) ? $_SESSION['myvar'] : ""; ?>
<input type="text" name="myans">
<input type="submit" value="Send">
<?php echo isset($_SESSION['result']) ? $_SESSION['result'] : ""; ?>
</form>
</body>
</html>
I've done this so often before on different websites, but can't get it to work now.
I've got a simple form that posts perfectly well using a submit button, but for a specific reason I actually need it to submit via a url link instead. I'm using submit(). The form submits, but the data isn't posting.
What am I missing?
<html>
<body>
<?
if(isset($_POST['bar'])) { echo 'testing button<br>'; }
if(isset($_POST['information'])) {
echo $_POST['information'];
echo '</br>Info successfully posted.';
}
?>
<form action="test.php" method="post" id="fooform">
Hello World.<br>
Select checkbox: <input type="checkbox" id="information" name="information" value="yes">
<input type="submit" name="bar" value="Send"><br>
Confirm and Post<br>
Post Directly
</form>
<script type="text/javascript">
function SubmitForm(formId) {
var oForm = document.getElementById(formId);
alert("Submitting");
if (oForm) { oForm.submit(); }
else { alert("DEBUG - could not find element " + formId); }
}
</script>
</body>
</html>
The form starts to submit, then the href of the link is followed, and this cancels the form submission.
If you are using old-style onclick attributes, then return false; at the end to prevent the default action.
You would, however, be better off using a submit button (you are submitting a form). You can use CSS to change its appearance.
Try this code :
<html>
<body>
<?php
if (isset($_POST['bar'])) {
echo 'testing button<br>';
}
if (isset($_POST['information'])) {
echo $_POST['information'];
echo '</br>Info successfully posted.';
}
?>
<form action="test.php" method="post" id="fooform">
Hello World.<br>
Select checkbox: <input type="checkbox" id="information" name="information" value="yes">
<input type="submit" name="bar" value="Send"><br>
Confirm and Post<br>
Post Directly
</form>
<script type="text/javascript">
function SubmitForm(formId) {
var oForm = document.getElementById(formId);
alert("Submitting");
if (oForm) {
oForm.submit();
}
else {
alert("DEBUG - could not find element " + formId);
}
}
</script>
</body>
</html>
try to submit form with form id in jquery
<a class="submit">Post Directly </a>
$('a.submit').click(function(){
$('#fooform').submit();
})