I'm working on a form.php file which is structured below:
<form action="action.php" method="post">
<input name="answer" type="text">
<input name="submit" type="submit" value="Submit">
<input name="reset" type="reset" value="Reset">
</form>
...and I want to add some php or javascript code which will read the value of the input field that the user will type and if the value is equal to a then echo true else echo false. Until now, I made some attempts like the one below but don't work.
<?php
$_POST($answer);
if ($answer == "a") {
echo "True";
} else {
echo "False";
}
?>
Maybe is not that simple as I think. Any ideas or better suggestions?
You must retrieve the named value 'answer' on the $_POST array into your var $answer:
<?php
$answer = $_POST['answer'];
if ($answer == "a") {
echo "True";
} else {
echo "False";
}
?>
See docs for further reference!
Your code was quite correct I've just added a few improvements
<?php
$answer = isset($_POST['answer']) ? $_POST['answer'] : null;
if ($answer == "a") {
echo "True";
} else if (!is_null($answer)) {
echo "False";
}
?>
Related
So I want to create a simple result page that lets users download their results using the given code.
This is the script:
<form action="" method="post" >
<input type="text" name="logincode">
<input type="submit" name="send">
</form>
<?php
$name = $_POST['logincode'];
$filename = $name.'/'.$name.'pdf';
header('Location: ./'$filename'');
?>
The principle is when the user writes into the input field, for example (1234) and hits enter, it should redirect him to:
./1234/1234.pdf
I don't know where the mistake is in my code.
Few issues,
Your header should be before anything else as #showdev mentioned in a comment.
You're missing a . between filename and extension
You also have a syntax error in the header trailing ''
And you should exit redirect headers.
You should also be checking your variables as you go, plus check the file exists, so you can show errors.
<?php
// check post request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$errors = [];
// check logincode is set and a number
if (!isset($_POST['logincode']) || !is_numeric($_POST['logincode'])) {
$errors['logincode'] = 'Invalid login code';
} else {
$name = $_POST['logincode'];
// check file is found
if (!file_exists($name.'/'.$name.'.pdf')) {
$errors['logincode'] = 'Your results are not ready.';
}
// now check for empty errors
if (empty($errors)) {
exit(header('Location: ./'.$name.'/'.$name.'.pdf'));
}
}
}
?>
<form action="" method="post">
<?= (!empty($errors['logincode']) ? $errors['logincode'] : '') ?>
<input type="text" name="logincode">
<input type="submit" name="send">
</form>
You are missing a “.” before pdf aren’t you?
And also wrong header('Location: ./'$filename'');
Try this :)
<?php
$name = $_POST['logincode'];
$filename = $name.'/'.$name.'.pdf';
header('Location: ./'.$filename);
?>
It's very insecure code!
Major changes below:
write test for user input data TODO by you
change order PHP block code first, form (HTML) code next in snippet
add test is post request_method before any $_POST['...']; in snippet
add .(dot) before filename extension i $filename in snippet
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = $_POST['logincode'];
$filename = $name.'/'.$name.'.pdf';
header('Location: ./'$filename'');
}
?>
<form action="" method="post" >
<input type="text" name="logincode">
<input type="submit" name="send">
</form>
<form action="" method="post" >
<input type="text" name="logincode">
<input type="submit" name="send">
</form>
<?php
if($_POST){
$name = $_POST['logincode'];
$filename = $name.'/'.$name.'.pdf';
header('Location: ./'.$filename.'');
}
?>
I'm developing a web application and I want to get the answer(yes or no) from user when the deactivate button is pressed. I want to ask him if you want or not to deactivate the account. I'm using PHP to set active status to = 1 when deactivated and 0 to activated.
I want to get the result and verify in PHP if the query runs or not.
I would appreciate if someone helps me, thanks. Here is the code:
if(isset($_POST['desativar']))
{
$login = $_SESSION['login'];
mysqli_query($conexao,"UPDATE usuarios SET ativo_usuario = 1 WHERE login_usuario='$login'");
}
You can use onsubmit attribute.
Example
function confirmDesactiv()
{
return confirm("Are you sure ?")
}
<form method="POST" action="yourphp.php" onsubmit="return confirmDesactiv()">
<button type="submit">Delete my account</button>
</form>
try it.
function confirm_delete(){
if(confirm("Are you sure you want to delete this..?") === true){
return true;
}else{
return false;
}
}
<input type="button" Onclick="confirm_delete()">
You can use PHP to make something like a confirmation box. Below is a little smaple code to show you how:
<?php
session_start();
if (isset($_POST['submit'])) {
$_SESSION['postdata'] = $_POST;
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else if (isset($_POST['confirm']) && $_POST['confirm'] == 'yes') {
// Do stuff that should only be done after confirming
} elseif (isset($_POST['confirm']) && $_POST['confirm'] == 'no') {
// Cancelled, redirect back to page
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
?>
<?php if (isset($_SESSION['postdata']) && !isset($_POST['confirm'])): ?>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
Are you sure you want to do this?<br />
<input type="submit" name="confirm" value="yes">
<input type="submit" name="confirm" value="no">
</form>
<?php else: ?>
<!-- Your form here -->
<?php endif; ?>
If you don't want to use AJAX, and assuming your page is called index.php:
<?
$deactivateStatusDisplay = "display: none"; // Initially, do not display a status.
$deactivateStatusMsg = ""; //Status message is initialized as blank.
$queryRan = false; // Just a flag to know if the user clicked deactivation link.
if( 1 === $_GET['deactivate'] ){
$deactivateStatusDisplay = "display: block";
$deactivateStatusMsg = "Your account will be deactivated.";
$queryRan = true;
}
?>
<!DOCTYPE html >
<html>
<head>
<!-- ALL YOUR METADATA -->
</head>
<body>
<div>Do you want to deactivate your account?</div>
DEACTIVATE
<div id="status" style="<? echo $deactivateStatusDisplay ?>"><? echo $deactivateStatusMsg ?></div>
</body>
</html>
**JS**
<script type="text/javascript">
function confirmDesactiv()
{
var flag = confirm("Are you sure ?");
if(flag)
window.open("yourphp.php?id=" + 1);
else
window.open("yourphp.php?id=" + 0);
}
</script>
**HTML**
<form method="POST" action="">
<button type="submit" onclick="confirmDesactiv()">Desactiv my account</button>
</form>
**PHP**
<?php
echo $_GET['id'];
if(isset($_GET['id']) && $_GET['id'])
{
//your update query will come here
}
?>
I'm creating small shopping-cart program, I'm using following code to input values.
<input type="button" value="Add to Cart : <?php echo $row['PART_NO']; ?>" onclick="addtocart('<?php echo $item; ?>')" />
value goes through following javascript code.
function addtocart(pid){
alert(pid);
document.form1.productid.value=pid;
document.form1.command.value='add';
document.form1.submit();
}
<body>
<form name="form1">
<input type="hidden" name="productid" />
<input type="hidden" name="command" />
</form>
<?php
if ( isset($_REQUEST['command']) && $_REQUEST['command'] == 'add' && $_REQUEST['productid']>0 ){
$pid=$_REQUEST['productid'];
addtocart($pid,1);
header("location:shoppingcart.php");
exit();
}
?>
when I'm inserting productid like 02190249 it goes through javascript code and php code and loading the shoppingcart.php. but inserting productid like PF161202 its not loading the shoppingcart.php. how can I pass values like PF161202 to php code through js.
Remove $_REQUEST['productid']>0 from your php code. It is checking only for numbers(02190249) which is greater then 0 but as per your question you are passing a string(PF161202).
<?php
if ( isset($_REQUEST['command']) && $_REQUEST['command'] == 'add' && ($_REQUEST['productid'] != '')){
$pid=$_REQUEST['productid'];
addtocart($pid,1);
header("location:shoppingcart.php");
exit();
}
?>
I am trying to make the div, "yourpick," hide once the POST query is successful. I know I'm checking for the POST in the middle of my form, but can we work around this. Thanks.
echo '<div class="yourpick" style="display:block;">
YOUR PICK:<br><form method="post" action="draft.php">';
echo '<input type="radio" name="pick" value="user1">User1<br>';
if(isset($_POST["pick"])){
$pick = $_POST["pick"];
$picksql = "UPDATE picks SET playerpick='" . $pick . "' WHERE id=$id AND picknum=$picknum";
if ($mysqli->query($picksql) === TRUE) {
echo "Pick Successful!";
echo "<script>document.getElementById('yourpick').style.display = 'none';</script>";
} else {
echo "Error Ocurred. Please contact commisioner.";
}
}
echo "<input type='submit' name='submit' /></form></div>";
It is best imo to use php alternative syntax in the HTML, so if isset($_POST["pick"]), then hide the div:
<?php if(isset($_POST["pick"])): ?>
<div class="yourpick" style="display:block;">
YOUR PICK:<br><form method="post" action="draft.php">
<input type="radio" name="pick" value="user1">User1<br>
<input type="submit" name="submit"></form></div>
<?php endif; ?>
Makes your code all nice and tidy. :)
You do not need Javascript for this:
if (isset($_POST["pick"])) {
$pick = $_POST["pick"];
$picksql = "UPDATE picks
SET playerpick = '$pick'
WHERE id = $id AND picknum = $picknum";
if ($mysqli->query($picksql) === TRUE) {
echo "Pick Successful!";
} else {
echo "Error Ocurred. Please contact commisioner.";
}
}
else {
echo '<div class="yourpick" style="display:block;">'.
'YOUR PICK:<br><form method="post" action="draft.php">'.
'<input type="radio" name="pick" value="user1">User1<br>'.
'<input type="submit" name="submit"></form></div>';
}
Sorry, but I'm not pointing out the obvious security risks of this code.
My code looks like this:
form action="familytree.php" method="post">
<?php
foreach ($spouses as $spouse) {
if (!empty($spouse['mname'])) {
$name = $spouse['fname'].' '.$spouse['lname'].' ('.$spouse['mname'].')';
}
else {
$name = $spouse['fname'].' '.$spouse['lname'];
}
if ($spouse['ended'] == '1') {
$married = '';
$divorced = 'checked';
}
else {
$married = 'checked';
$divorced = '';
}
?>
<div class="form_section dates">
<h3><?php echo $name; ?></h3>
<p>
<input type="radio" id="married_option" name="married_divorced_options" <?php echo $married; ?> value="1"/>
<label for="edate">Married</label>
<input type="radio" id="divorced_option" name="married_divorced_options" <?php echo $divorced; ?> value="1"/>
<label for="sdate">Divorced</label>
</p>
<div class="half" style="display: inline">
<input type="text" name="sdate_<?php echo $spouse['individual_id']?>" id="sdate_<?php echo $spouse['individual_id']?>" value="<?php echo $spouse['start_date']; ?>" placeholder="Rašykite sutuoktuvių datą čia"/>
<?php echo $this->formError->error("sdate_".$spouse['individual_id'].""); ?>
</div>
<div id="divorced" class="half" style="display:none">
<input type="text" name="edate_<?php echo $spouse['individual_id']?>" id="edate_<?php echo $spouse['individual_id']?>" value="<?php echo $spouse['end_date']; ?>" placeholder="Rašykite skyrybų datą čia"/>
<?php echo $this->formError->error("edate_".$spouse['individual_id'].""); ?>
</div>
</div>
<?php
}
?>
<p class="submit">
<input class="first-btn" type="submit" id="edit-relationship" name="edit-relationship" value="Edit"/>
</p>
</form>
jQuery("#divorced_option").click(function() {
document.getElementById("divorced").style.display = "inline-block";
});
jQuery("#married_option").click(function() {
document.getElementById("divorced").style.display = "none";
});
What I would like to know is how to check if a radio button is clicked when you don't know its full name, only half of it. For example, #divorced_option is not full name, it should be something like this #divorced_option_161, #divorced_option_161... So, the code should check if the radio button that has divorced_option in its name is clicked. Is there a way to achieve this?
EDIT
It works with jQuery("[id^='married_option']").click(function(){}). But I forgot to mention in my original question that the element divorced isn't full name as well, it should be divorced_161, divorced_162, depending of the name of the radio button that is clicked. How can I hide the element that matches with the radio button?
Use the attribute starts with selector (ex. [name^="value"]):
jQuery("[id^='divorced_option']").click(function() {
document.getElementById("divorced").style.display = "inline-block";
});
jQuery("[id^='married_option']").click(function() {
document.getElementById("divorced").style.display = "none";
});
Have a look at the jQuery selectors.
The 'Attribute Contains' selector would be useful here, which means your code would be :
jQuery("[id*='divorced_option']").click(function() {
document.getElementById("divorced").style.display = "inline-block";
});
jQuery("[id*='married_option']").click(function() {
document.getElementById("divorced").style.display = "none";
});
You can select the elements based on the #divorced_option_[number] pattern while checking if they are selected like this:
$("input[id*=divorced_option]:checked");
If you would like to check wether the divorced_option substring is in the name="" attribute of the radio element, then change the id from the selector to name, like so:
$("input[name*=divorced_option]:checked");
After this, just check wether or not jQuery returned an actual element.