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
}
?>
Related
I have a PHP to verify the HTML form (post method). If the value doesn't match, the error message should be added at the HTML page. I test the embedded JS script in console, it works. But it doesn't work in PHP. How can I fix it? Thank you
Here is my code
<!DOCTYPE html>
<body>
<form action="http://localhost/submitTest.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<div id="submitField">
<input type="submit">
</div>
</form>
</body>
</html>
<?php
if ($_GET["name"] == 1 && $_GET["email"] == 2) {
header('Location: http://localhost/table.html');
} else {
$url = 'http://localhost/submitTest.html';
echo "<meta http-equiv='Refresh' content='0;URL=$url'>";
echo "
<script>
var messageP = document.createElement('span');
messageP.style.color = 'red';
var parent = document.getElementById('submitField');
parent.appendChild(messageP);
messageP.innerHTML = 'not match';
</script>";
}
?>
I want to do something like thiserror message
i'm doing a very rookie password signup thing for my web development project and i'm stuck here
<script>
<?php
if ( isset($_POST['enter']) ){
if ($_POST['password']=='0000'){
echo('document.getElementById("adminsection").style.display = "block";
document.getElementById("passsection").style.display = "none" ;');
}
else{
echo ("alert('password incorrect');");
}
}
?>
</script>
for some reason this part doesn't seem to work when the condition is met:
echo('document.getElementById("adminsection").style.display = "block";
document.getElementById("passsection").style.display = "none" ;');
adminsection and passsection are just section tags that contain the elemnts of the page and they look kinda like this
<form style="width:100%; margin:10% 0 10% 0" action="administrator123.php" method="POST">
<section id="passsection">
<input style="margin-left:-5px" id="passfield" name="password" type="password" placeholder="****">
<input type="submit" id="password" name="enter" value="enter">
</section>
<section id="adminsection">
<p>hey</p>
</section>
</form>
the goal behind this code is to hide the passsection and show the adminsection upon entering the correct password
i'd appreciate it very much if you provided me with a solution that doesn't involve jQuery
You're mixing javascript and PHP the wrong way.
Normal form submission. The order of operations are:
you have a form in html (you're missing the form element)
user submits the form
this sends the submit to the server causing a page load/reload
server-side PHP checks if the password is good
The newly loaded page does stuff with the PHP output.
<?php
if ( isset($_POST['enter']) ){
if ($_POST['password']=='0000'){
$loggedin = true;
} else {
$error="Password was incorrect";
}
}
?>
<?php if (!$loggedin) {?>
<section id="passsection">
<?php if ($error) {?>
<div class='error'>
<?php echo $error;?> </div>
<?}?>
<form method='post'>
<input style="margin-left:-5px" id="passfield" name="password" type="password" placeholder="****">
<input type="submit" id="password" name="enter" value="enter">
</form>
</section>
<?}?>
Ajax form submission. The order of operations are:
you have a form in html (you're missing the form element)
user submits the form
javascript prevents the form from reloading the page, and sends the form data through ajax to the server
server-side PHP checks if the password is good and outputs the response in json_encode() format
ajax function gets response and uses that data to provide feedback.
Your php will live in a separate file
doLogin.php
<?php
$loggedin = false;
if ( isset($_POST['enter']) ){
if ($_POST['password']=='0000'){
$loggedin = true;
} else {
$error="Password was incorrect";
}
}
$response = array('isLoggedIn' => $loggedin);
if ($error) $response['error'] = $error;
echo json_encode($response);
?>
document.querySelector('#passsection form').addEventListener('submit', function(e) {
e.preventDefault(); // stop the page from reloading
var request = new XMLHttpRequest();
let url = "/php/doLogin.php";
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/json");
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
var jsonData = JSON.parse(request.response);
if (jsonData.isLoggedIn) {
document.querySelector('#passsection').style.display = "none"
} else if (jsonData.error) {
document.querySelector('#passsection form .error').innerHTML = jsonData.error
}
}
};
let data = JSON.stringify({
"passfield": document.getElementById("passfield").value
});
request.send(data);
});
<section id="passsection">
<div class='error'></div>
<form method='post'>
<input style="margin-left:-5px" id="passfield" name="password" type="password" placeholder="****">
<input type="submit" id="password" name="enter" value="enter">
</form>
</section>
The form was working for a while but I moved some code around and can't revert (A lesson learned), now the code isn't working like it's supposed to. In a nutshell, User clicks delete button > Delete button sends specific Entry ID to function, Function gets form ID, "Confirms delete", then should send to my delete_entry.php code. Now, form is always submitting even when I hit "NO" and I added an alert to tell me which route it goes.
I've tried commenting out the form, and it still submits, so I don't think it's explicitly tied to the confirm function (Could be crazy though)
if ($entry['SubEntryID'] == "0") { ?>
<div id="post"><!-- This is the main post-->
<div id="main">
<div id="title">
<?php echo $entry['EntryID']; ?>
<?php echo $entry['Title']; ?>
</div><br />
<p><?php echo $entry['Body']; ?></p><br />
<div id="postinfo">
At: <?php echo $entry['CreateDate']; ?><br/>
Posted by - <?php echo $entry['UserName']; ?>
</div>
<!-- Start the form for the delete button -->
<form action="Delete_entry.php" method="post" id="Delete<?php echo $entry['EntryID'];?>">
<input type="hidden" readonly="true" name="EntryID" value="<?php echo $entry['EntryID']; ?>" />
<input type="hidden" readonly="true" name="UserID" value="<?php echo $entry['UserID']; ?>" />
<?php if ($userid == 1 || $userid == $entry['UserID']) { ?>
<input onclick="confirmdelete('Delete<?php echo $entry['EntryID'];?>')" type="image" src="redx.png" alt="Delete Post" id="btnDelete" value="Delete Post"/>
<?php } ?><br />
</form>
</div>
function confirmdelete(eid) {
var retval = confirm("Are you sure you want to delete?" + eid + "?");
if (retval == true) {
alert("You said Yes");
document.getElementById(eid).submit();
}
else
{
alert("You said No");
}
}
I want the delete button to call the function, the function to respond by submitting the form if it's true, and cancelling the form submission if false. The form page should only get called if confirm is true, and then submit()
Firstly the confirmdelete() is not returning any true/false back so there is no code that stops the form from submission. Secondly, a form will submit anyway even if the function returns false because you have 2 submits (the form and the onclick).
Move the function call to onsubmit() of the form. Remove the onclick because the input type image submits the form by default. Here is the code:
Form:
<form action="Delete_entry.php" method="post"
id="Delete<?php echo $entry['EntryID'];?>"
onsubmit="return confirmdelete(<?php echo $entry['EntryID'];?>)">
Then the button (onclick removed):
<input type="image" src="redx.png" alt="Delete Post" id="btnDelete" value="Delete Post" />
Finally the JavaScript (returns true/false):
function confirmdelete(eid) {
if (confirm("Are you sure you want to delete?" + eid + "?")) {
alert("You said Yes");
return true;
}
else
{
alert("You said No");
return false;
}
}
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 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";
}
?>