php form will not submit unless the checkbox is ticked - php

my form is unable to submit unless the checkbox is ticked, I am really unsure as to why this is.
further, if the checkbox is ticked it fails to update the database, there is no issue with the function I am using or the query as i have checked that directly on the db.
Any help would be hugely appreciated, and please feel free to ask any questions if there is anymore information i can give
<?php
include 'core/init.php';
protect_page();
include 'includes/overall/header.php';
$page = $_GET['page'];
$email = $_GET['user'];
$p_id = project_id_from_project_name($page);
$supervisor = supervisor_from_email($email, $p_id);
$user_id = user_id_from_email($email);
?>
<h1>Add A User to the Project</h1>
<?php
if (isset($_GET['form_submit']) === true && empty($_GET['form_submit']) === false) {
echo 'You\'re user has been added successfully!<br /><br />';
echo 'Please click here to return to Your Projects';
} else {
if (empty($_POST) === false && empty($errors) === true) {
$page = $_GET['page'];
$p_id = project_id_from_project_name($page);
$supervisor_update = ($_POST['supervisor'] == 1) ? 1 : 0;
$update_project_member_data = array(
'project_id' => "$p_id",
'project_name' => "$page",
'project_member_id' => "$user_id",
'supervisor' => "$supervisor_update"
);
update_project_member_data($p_id, $update_project_member_data);
header('Location: update_user.php?page=' . $page .'&user=' . $email .'&form_submit=1');
exit();
} else if (empty($errors) === false) {
echo output_errors($errors);
}
?>
<form action="" method="post">
<ul>
<li>
Email Address: <?php echo $email ?>
</li>
<li>
Set user as Supervisor?<br />
<input name="supervisor" type="checkbox" <?php if ($supervisor == 1) {?> checked="checked"<?php }?>/>
</li>
<li>
<input type="submit" value="Update User">
</li>
</ul>
</form>
<?php
}
include 'includes/overall/footer.php'; ?>

I believe the problem is with the condition you have:
empty($_POST) === false
Since your form is very basic and only has the one input. The $_POST array is only populated with values when that input is checked. Unchecked it doesn't pass any values in the $_POST array. Normally, the submit button would pass a value, but since you didn't have the "name" attribute on there, it doesn't.
You can either try adding the name attribute to the submit button or just add a hidden value inside the FORM element such as:
<input type="hidden" name="action" value="submitted" />

I think what is happening here is that there is no data to post if you do not check the box. You can check for the request method, $_SERVER['REQUEST_METHOD'] instead of empty($_POST).
edit: to clarify, the post happens but the if condition evaluates to false

Related

Refresh a PHP page after checking/unchecking a checkbox

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()
})
})()

Codeigniter checking checkbox value

I'm using CodeIgniter and I have a form with a checkbox that allows the user to check and remove their uploaded photo.
In my controller I use if(isset($checked) == 1) to check if the user wants to remove the photo.
$photo_to_table will set empty and pass to $this->tank_auth->update_user() to perform db update, and set photo field to become empty in table. Otherwise, it will remain the same photo.
But in my code, whether I check it or not, when I click UPDATE button, it keeps removing the photo, I wonder why is it happening?
Can someone please go through my code and give an advise?
Controller:
$user_id = $this->session->userdata('user_id');
$profile = $this->users->get_profile_by_id($user_id);
if(!empty($_FILES['photo']['name']))
{
//image upload process
}
else
{
$checked = $this->input->post('remove');
if(isset($checked) == 1)
{
$photo_to_table = '';
// here will do remove process to delete file in directory
}
else
{
$photo_to_table = $profile->photo;
}
}
if($this->form_validation->run()) { // validation ok
if(!is_null($data = $this->tank_auth->update_user(
$this->form_validation->set_value('name'),
$this->form_validation->set_value('country'),
$this->form_validation->set_value('website'),
$photo_to_table
)))
{
// success
$this->session->set_flashdata('msg', 'Profile has been updated');
redirect(current_url());
}
}
View:
<?php echo form_open_multipart($this->uri->uri_string()); ?>
<table border="0">
<?php
if(!empty($uphoto)){
?>
<tr>
<td>
<div>
<img src="<?php echo base_url().$userpath.$uphoto; ?>" />
</div>
<div>
<input id="remove" type="checkbox" name="remove">
<label for="remove">Remove photo</label>
</div>
</td>
</tr>
<?php
}
?>
Thanks.
What you need to do here is to change this line ...
if(isset($checked) == 1){
to
if((int) $checked == 1){
The reason is that the variable $checked will always be set whether its value is 1 or not. $checked = $this->input->post('remove'); will return NULL if the 'remove' is not set in the POST data.
Please write proper value in your checkbox :-
<input id="remove" type="checkbox" name="remove">
Write some value then check it :-
for e.g :
<input id="remove" type="checkbox" name="remove" value="1">
In php :-
if($checked == 1) {
// do whatever u want
}
Try:
<input id="remove" type="checkbox" name="remove" value="1">
remove isset
its because by default in your CI Controller you get input value using
$checked = $this->input->post('remove');
whether is has a value or not your variable now exist..
Use this if it can help.
$checked = (isset($_POST['checkbox']))?true:false;

php check post contains a variable [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
this is my page when i run it i got the excption which sayes that the formSubmit is not define . i know that i have to check if the post contents that variable but i couldn't know the solution
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['formPassword']))
{
$errorMessage .= "<li> You forgot to enter your password!</li>";
}
if(empty($_POST['formName']))
{
$errorMessage .= "<li> You forgot to enter a name!</li>";
}
$varPassword = $_POST['formPassword'];
$varName = $_POST['formName'];
if(empty($errorMessage))
{
require('Document1.php');
User::add_user($varName, $varPassword);
exit;
//header("Location: normal.php");
}
}
?>
<html>
<head>
<title>SIGN UP</title>
<style type="text/css">
<!--
.style1 {
font-size: xx-large;
color: #0000CC;
}
-->
</style>
</head>
<body>
<p align="center"><br>
<span class="style1">SIGN UP</span></p>
<p> </p>
<form action="myform1.php" method="post">
<p>
What is Your NAME ?<br>
<input type="text" name="formName" maxlength="50" value="" />
</p>
<p>
What is Your PASSWORD ?<br>
<input type="text" name="formPassword" maxlength="50" value="" />
</p>
<?php
/*
?>
<p>
What is Your Email ?<br>
<input type="text" name="formEmail" maxlength="50" value="" />
</p>
*/
?>
<input type="submit" name="formSubmit" value="Submit" />
<input type=reset value = "delete fields ">
</form>
</body>
</html>
any help would be appreicated
The reason is because the PHP code also runs the very first time when the page loads, even though the form isn't yet submitted. The solution is to change your first IF statement as follows:
<?php
if(isset($_POST['formSubmit']) && $_POST['formSubmit'] == "Submit")
{
// OTHER CODE REMAINS AS IT IS
}
?>
It will now check that not only $_POST['formSubmit'] is set to "Submit" but also that it exists. When the page first loads, $_POST['formSubmit'] will not be available and therefore no exception will be thrown.
Hope it helps!
I suggest using .
if (isset($_POST['formSubmit']) && ($_POST['formSubmit'] == "Submit")) {
/* ... */
}
isset() method will check if value exists
You can check that its a $_POST request with $_SERVER['REQUEST_METHOD'] === 'POST' also add errors to an array this way you can place the errors where you want.
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){
$error = array();
if(empty($_POST['formPassword']))
{
$error['pass'] = "You forgot to enter your password!";
}
if(empty($_POST['formName']))
{
$error['name'] = "You forgot to enter a name!";
}
if(empty($error))
{
require('Document1.php');
User::add_user($_POST['formName'], $_POST['formPassword']);
exit;
//header("Location: normal.php");
}
}
?>
Then if error just add <?php echo isset($error['name']) ? $error['name'] : null ?> where you want the message specific to the error. like next to the input for name.
It's always a good practice to use isset() to check if a variable is set.
Change
if($_POST['formSubmit'] == "Submit")
to
if(isset($_POST['formSubmit']) && $_POST['formSubmit'] == "Submit"){
//rest of the code
}
See also: empty()
Before you try to get the value of $_POST['formSubmit'], you should check if it is set with isset($_POST['formSubmit'])
if (isset($_POST['formSubmit']) && $_POST['formSubmit'] == "Submit") {
// your code
}
I think it also work with:
if ($_POST['formSubmit'] && $_POST['formSubmit'] == "Submit") {
// your code
}
but is better to use isset()
Rather than using isset() everywhere, I prefer to declare default values. For example...
$defaults = array(
'formSubmit' => '',
'formPassword' => '',
'formName' => '',
);
$form = $_POST + $defaults;
if ($form['formSubmit'] == 'Submit') {
// ...

Form values should not clear

I have a form to submit my contact info.
and i'm fetching form fields using php like:
if(isset($_post['submit']))
{
//submit cantact info
}
else
{
//bad user
}
my problem is: if the user is failed to submit form the "form values should not clear"....
but form values are clearing on click submit button..! so anyone know how to prevent clear form values?
you have to populate these fields manually.
the general idea stands for using POST/Redirect/GET method
after receiving POST data you have to check it and raise error flag
and in case of some errors you have to show the same form back, with filled inputs and corresponding error messages.
here is a rough example:
<?
$err = array();
if ($_SERVER['REQUEST_METHOD']=='POST') {
//performing all validations and raising corresponding errors
if (empty($_POST['name']) $err[] = "Username field is required";
if (empty($_POST['text']) $err[] = "Comments field is required";
if (!$err) {
// if no errors - saving data
// and then redirect:
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
} else {
$form['name'] = $form['comments'] = '';
}
include 'form.tpl.php';
?>
and then in the form.tpl.php template make it like this:
<? if ($err): ?>
<? foreach($err as $e): ?>
<div class="err"><?=$e?></div>
<? endforeach ?>
<? endif ?>
<form>
<input type="text" name="name" value="<?=$form['name']?>">
<textarea name="comments"><?=$form['comments']?></textarea>
<input type="submit">
</form>
You have to (manually) put the submitted values in the form elements. Example:
<input type="text" name="username" value="<?=( isset( $_POST['username'] ) ? $_POST['username'] : '' )?>" />
You need to keep track of the form values. One suggestion is to setup an array of default values that is used when presenting the form markup.
On POST, you then merge the post data. For example
$formData = array(
'foo' => '',
'bar' => 'default value',
'baz' => ''
);
if ('POST' == $_SERVER['REQUEST_METHOD') {
$formData = array_merge($formData, $_POST);
// do validation, handle success
}
Then, in HTML
<input name="foo" value="<?php echo htmlspecialchars($formData['foo']) ?>">
<!-- etc -->

show the form only if submit is not set

I am trying to show the form only if submit is not set, and if set then upload file and show link to the same page so that a new file could be uploaded again.
It shows the form even after I click on the submit button. I have not added an upload script now.
<body>
<?php
if (isset($_POST['submit']))
{
$output_form == 'no';
echo 'hiiiii';
}
else {
$output_form = 'yes';
}
if($output_form = 'yes')
{
?>
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="file" name="uploadpic" />
<input type="submit" value="Upload" name="submit" />
</form>
<?php
}
?>
</body>
$output_form == 'no'; should be $output_form = 'no';
if ($output_form = 'yes') should be if ($output_form == 'yes')
= is assignment, whereas == is a comparison.
Also, your form will use GET because you did not ask it to use POST with method="POST".
You're missing your method on the form element.
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
You can also use print_r($_POST) to see what's in the array.
Here's an example of it working, as well as the code.
http://www.wecodesign.com/demos/stackoverflow-7018639.php
if($output_form = 'yes')
should be
if($output_form == 'yes')
The way you have it now, you're assigning a value.
It should be
if($output_form == 'yes')
You doing assignment, use comparison:
if($output_form == 'yes')
Ensure that you're actually SETTING the no value as well:
$output_form == 'no';
Should be
$output_form = 'no';

Categories