Disable all input buttons on page if no PHP session exists - php

I'm doing a site with a voting system. What i want is to disable all input buttons (the ability to vote) if the user isnt logged in (ie. a session doesnt exist). How do i do a check in PHP at the top of the page and then allow/disallow the input buttons? Would i use CSS or jQuery?

Somewhere in the code check if the session is not set:
if(!isset($_SESSION['some_key'])){
$disable = true;
}else{
$disable = false;
}
Then, in the html:
<input type="radio" name="" value=""<?=($disable ? " disabled=\"disabled\"" : "");?>/> Vote 1
<input type="radio" name="" value=""<?=($disable ? " disabled=\"disabled\"" : "");?>/> Vote 2
<input type="radio" name="" value=""<?=($disable ? " disabled=\"disabled\"" : "");?>/> Vote 3
But you still have to check at the serverside before you accept the vote, if the person has voted before, because this form can be edited easily to post the data again and again.

<?php if(!isset($_SESSION['logged']))
{
echo "<script language=\"javascript\">";
echo "$(document).ready(function()
{
$('input[type=submit]').each(function() { this.attr('disabled', 'disabled') });
});</script>"
}
?>

You should dynamically generate a correct HTML code. Something like this:
<?php if(isset($_SESSION['logged'])): ?>
<form> voting form </form>
<?php else: ?>
<p>Sign in to vote</p>
<?php endif ?>
You should also check whether user is logged in before you process a form:
if (isset($_SESSION['logged']) && isset($_POST['vote'])) {
// process form
}

Related

i need js insert mysql if button value is checked

<script type="text/javascript">
$('.next').click(function () {
var radio_check_val = "";
for (i = 0; i < document.getElementsByName('<?php echo $result['id']; ?>').length; i++) {
if (document.getElementsByName('<?php echo $result['id']; ?>')[i].checked) {
radio_check_val = document.getElementsByName('<?php echo $result['id']; ?>')[i].value;
}
}
if (radio_check_val == "1")
{
<?php
$res1 = mysqli_query($con, "INSERT INTO quiz_log (email,question,answer_choose,answer_correct,category,level) VALUES ('$email','$question','$a1','$answerko','$category','$qlevel')");
?>
} else if (radio_check_val == "2"){
<?php
$res2 = mysqli_query($con, "INSERT INTO quiz_log (email,question,answer_choose,answer_correct,category,level) VALUES ('$email','$question','$a2','$answerko','$category','$qlevel')");
?>
}
});
</script>
It insert both SQL query. if the radio button is checked it insert also the other SQL query. I need insert query if the radio button 1 is checked, and if the radio button 2 is checked the sql query will insert.
PHP is executed on the server before the browser executes JavaScript. So both SQL queries will already be done before the visitor can see the result. He could chose for example one of the results, you can show/hide something using JavaScript and send a choice back to the server.
It looks, as you want to depend on visitors choice, wich query will be done. In this case you have to present a form to the browser, send back the form data and then process the query on another PHP-page.
<?php if(array_key_exists('myradio', $_GET)): ?>
<?php if($_GET['myradio'] === '1'): ?>
First option has been selected.
<?php endif ?>
<?php if($_GET['myradio'] === '2'): ?>
Second option has been selected.
<?php endif ?>
<?php endif ?>
<form method="get" action="">
<input type="radio" name="myradio" value="1"> Option 1
<input type="radio" name="myradio" value="2"> Option 2
<input type="submit">
</form>
In this example the form data is sent back to the same PHP file. You can split it into two files and give the URL of the second one into the action attribute of the <form>.

PHP Radio Buttons - Keep The Values in The Form after an Error

I'm building a contact page with email, name, etc. in HTML with PHP. I have radio buttons on my contact page as well. If the user submitted their name and checked a radio button but forgot to put an email in, the form processing page will flipped them back to the contact page with an error. I'm able to have my contact keep the values put in for their name (and email if user inputs it), but it does not keep the value checked in the radio button.
I'm new to PHP, so I bet it's a silly error on my part. Here's what I have for my Name Input:
Your Name:
<input type="text" name="name" <?php
if (isset($form['name'])) {
echo 'value="';
echo htmlentities($form['name']);
echo '"';
}
?>/>
I tried to do something similar to my Radio. Here's what I have for my Radio:
Are you New to our Business?<br>
<input type="radio" name="customer" value ="yes" <?php
if (isset($form['customer'])) {
echo 'value="';
echo htmlentities($form['customer']);
echo '"';
}
?>/>
Yes, I am!<br>
<input type="radio" name="customer" value="no"<?php
if (isset($form['customer'])) {
echo 'value="';
echo htmlentities($form['customer']);
echo '"';
}
?>/>
No, I am a returning customer!
I'm storing the values on the user input in an array called $form - that's why I have ($form['name]). I would like to it to continue doing that. Some other responses I have researched simply have an isset without the array part.
Hopefully I've provided enough information... Thanks for your help!
You need to do it like this:
if (isset($form['customer']) && $form['customer'] == "yes") {
echo 'checked="checked"';
}
and
if (isset($form['customer']) && $form['customer'] == "no") {
echo 'checked="checked"';
}
You need to change the if-conditional to the following:
<?php
if (isset($form['customer']) && $form['customer'] == "yes") {
echo 'checked';
}
?>/>
Replace the "yes" with "no" for the No part.

keeping checked checkbox state unless unchecked

I had asked this question but did not get a solution. By short explanation I would like the checked checkboxes to stay checked unless unchecked by the user: on page refresh.
I am able to keep the boxes checked on page refresh but when the page id changes(I have pagination) like index.php?page=2 the boxes get unchecked so is there a way that I can get the boxes to stay checked unless unchecked even if the page id changes?
I am displaying results from database and the user can filter results. If the user clicks on the next page for more results I would like to keep the checked boxes stay checked so that I can show filtered results from page 2. I really need help. Thanks
<form id="form" method="post" action="">
<input type="checkbox" name="sa" class="checkbox" <?=(isset($_POST['sa'])?' checked':'')?>/>Samsung<br>
</form>
<script>
$(document).ready(function(){
$('.checkbox').on('change',function(){
$('#form').submit();
});
});
</script>
I have tried this jquery function along with the above one but it doesn't work.
$("input.checkbox").each(function() {
var mycookie = $.cookie($(this).attr('name'));
if (mycookie && mycookie == "true") {
$(this).prop('checked', mycookie);
}
});
$("input.checkbox").change(function() {
$.cookie($(this).attr("name"), $(this).prop('checked'), {
path: '/',
expires: 365
});
});
I think this is what you need:
<input type="checkbox" name="sa" class="checkbox" value="yes"
<?php echo ($_POST['sa'] == 'yes')? ' checked="checked"':'' ?>/>Samsung<br>
The proper mark-up being
checked="checked"
to get that to stay active based on your condition.
This only occurs if you are continuing through other pages WITH the form being used to get to them. If you only expect people to use the form once, you should set a SESSION or GET variable to carry that value through other pages without the use of the form.
So, for example, keep the form almost the same, except change your condition and include this in your header, before you spit out the form -
<?php
session_start();
if(isset($_POST['changeit'])) {
if( $_POST['sa'] == 'yes') {
$_SESSION['checked'] = true;
} else {
$_SESSION['checked'] = false;
}
}
?>
then make you're condition for spitting out checked:
<input type="checkbox" name="sa" class="checkbox" value="yes"
<?php echo ($_SESSION['checked'] == true)? ' checked="checked"':'' ?>/>Samsung<br>
and include a hidden input to only check if the checkbox has changed.
<input type="hidden" name="changeit" />
that way, the condition for setting the session is only checked if the form checkbox was checked or unchecked... so your whole structure should look something like this -
<?php session_start(); ?>
<!DOCTYPE HTML>
<HTML>
<HEAD>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</HEAD>
<BODY>
<?php
if(isset($_POST['changeit'])) {
if( $_POST['sa'] == 'yes') {
$_SESSION['checked'] = true;
} else {
$_SESSION['checked'] = false;
}
}
?>
<form id="form" method="post" action="">
<input type="checkbox" name="sa" class="checkbox" value="yes"
<?php echo ($_SESSION['checked'] == true)? ' checked="checked"':'' ?>/>Samsung<br>
<input type="hidden" name="changeit" />
</form>
<script>
$(document).ready(function(){
$('.checkbox').on('change',function(){
$('#form').submit();
});
});
</script>
</BODY>
</HTML>
The fundamental note is that POST variables will not transfer over from page to page if the form isn't being used. The "action" is not called, thus the post is not sent. You have to use either COOKIES or SESSIONS or GET variables to have this cross over pages without the use of the form every time.
RCNeil's answer is correct, in that if the post key 'sa' is set, the checkbox will be checked="checked".
To expand on his answer, It doesn't have to be from a post value, it can be pulled from the database, or anywhere really. It just needs to return a boolean (True/False). The following would also work:
//Some logic
$YourVariable = true; //for example
//Then the checkbox conditional
<input type="checkbox" name="sa" class="checkbox"
<?=($YourVariable)?' checked="checked"':'')?>/>Samsung<br>
Will return as the checked="checked" and the checkbox marked by default. (Unless, bool false)
<input type="checkbox" name="sa" class="checkbox" checked="checked" value="forever"
<?=(isset($_POST['sa'])?:'')?>/>Samsung<br>
I guess this should work

Remembering Form Checkbox State With Initial Default Value

I've got a form with a checkbox. When a user first visits the page, I want the checkbox to be 'checked'. However, if they uncheck the box and then submit the page, I want it to remain unchecked (and to remain checked if they submit the page with it checked).
To determine when it has been checked and the form submitted, I'm currently doing:
<input type='checkbox' class='seeAll' name='seeAll' value='true' <?php if ($_POST['seeAll'] == 'true') echo checked; ?>>
This works great for leaving the box checked when needed, however, how would I go about ensuring it stays unchecked if they submit it that way, while also being checked if they revisit the page (such as by re-entering the URL)?
Thanks!
I don't know why it took me so long to come up with this answer, but after struggling with this, I realized I could just check the value of the checkbox via the $_POST, as I was doing before and could check if the user arrived at the page by some means other than the submit button by doing this:
<?php if(($_POST['seeAll'] == 'true') || !isset($_POST['submit'])) echo checked; ?>
If the user submitted the form, than isset($_POST['submit']) will be true and so if that's the case and $_POST['seeAll'] is empty, them obviously the user submitted an unchecked box. If isset($_POST['submit']) is false, then the user arrived on the page without submitting the form and I should check the checkbox as the 'default'.
So then my whole <input> tag looks like this:
<input type='checkbox' class='seeAll' name='seeAll' value='true' <?php if(($_POST['seeAll'] == 'true') || !isset($_POST['submit'])) echo checked; ?>>
Works just as I need!
NOTE:: This is differs from OP's question because it will remember the value of the checkbox even if the user goes away from the page (say, to www.facebook.com) and then back to the page. The OP wanted it to only remember the value of the checkbox when the page was posted to.
If you want a non permanent method you can use $_SESSION :
<?php
if (!isset($_SESSION)) {
session_start();
}
if ($_POST['seeAll'] == 'true' || !isset($_SESSION['seeAll'])) {
$_SESSION['seeAll'] = true;
} else {
$_SESSION['seeAll'] = false;
}
?>
<form method="POST">
<input type='checkbox' class='seeAll' name='seeAll' value='true'
<?php if ($_SESSION['seeAll']) echo 'checked'; ?>
/>
<input type='submit'/>
</form>
see: http://php.net/manual/en/session.examples.basic.php
One solution is to use both $_SESSION[""] and $_POST[""].
(See explanation and code below)
EXPLANATION
If $_SESSION["loadcount"] is not set, set it to 0.
With each if (isset($_POST["submit"], increase $_SESSION["load count"] by +1.
In the 'checked' option of the input type="checkbox", echo PHP. If if ($_SESSION["loadcount"] == 0) echo 'checked'. (Sets the checkbox to an initially checked state.)
Else, if (isset($_POST["agree"] echo 'checked', to remember the state checked by the user. (Remember the checked state set by user.
CODE
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php // session_firstload.php
// Check if $_SESSION is not set, set $_SESSION loadcount to 0
if (!isset($_SESSION["loadcount"]))
$_SESSION["loadcount"] = 0;
// When the user submits using POST Method
if (isset($_POST["submit"]))
{
// Increase $_SESSION["loadcount"] by +1
$_SESSION["loadcount"] = $_SESSION["loadcount"] + 1;
}
// Echoing for Debugging / Understanding
echo $_SESSION["loadcount"];
?>
<form action="session_firstload.php" method="post">
<input id="agree" type="checkbox" name="agree"
<?php
// If Check the Checkbox is $_SESSION["loadcount"] == 0
// Else 'remember' with (isset($_POST["agree"]
if ($_SESSION["loadcount"] == 0)
echo "checked";
else
{
if (isset($_POST["agree"]))
echo "checked";
}
?>
>I Agree<br>
<input type="submit" name="submit">
</form>
</body>
</html>

PHP - Form: save entries/selections on form submit

I have a PHP form that has some drop down selections and text field entries. If the user selects the wrong item from the dropdown, when they submit the form, I have it so that it will show an error message to the user and force the browser to go back to the previous page. The problem is that the user has to re-enter all of the information.
How do I make the form save the data until the form submit is successful?
EDIT:
Form submit method is $_POST and the form is being submitted to another page.
This would have to be done with strictly PHP as Javascript/Jquery solutions can be script blocked by more secure users.
Here you go. This will work, and is not dependent on Javascript:
form.php //the form page
<?php session_start(); ?>
<form method="post" action="action.php">
<input type="text" id="input1" value="<?php echo (isset($_SESSION['fields']) ? $_SESSION['fields']['input1'] : '') ?>" />
<input type="text" id="input2" value="<?php echo (isset($_SESSION['fields']) ? $_SESSION['fields']['input2'] : '') ?>" />
</form>
action.php //the action page
<?php
session_start();
//do your validation here. If validation fails:
$_SESSION['fields']['input1'] = $_POST['input1'];
$_SESSION['fields']['input2'] = $_POST['input2'];
//redirect back to form.php
?>
Is the form a POST or a GET? Either way, you have access to all the submitted fields in the PHP variables $_POST or $_GET. Within your HTML you can pass those values (if set), to the default value of each HTML input element. This way, if it is a first time, they will be blank, if there was an error, the values will repopulate.
If they're select values, you can do something like this:
<select name="my_select" id="my_select">
<option value="123"<?php if($_REQUEST['my_select'] == 123) echo ' selected="selected"; ?>>123</option>
</select>
If you have regular text inputs, you can simply apply the $_REQUEST variable to the value attribute:
<input type="text" name="my_text" value="<?php echo $_REQUEST['my_text'] ?>" />
I suggest a preventing the page from navigating away from the submission until the data is verified. Enter jQuery :)
<script type="text/javascript" src="jquery-library.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// Wait for the user to click on your button
$('#submit_button').click(function(){
// Check each form field for an appropriate value
if ($('#form_field1').val() != 'something I expect')
{
alert('Wrong submission!');
return false;
}
// Forward the user to some url location
window.location = 'url';
return false;
});
});
</script>

Categories