Even when the checkbox is unselected it is still returning the Value. I am passing the form through an Ajax request and printing the returned value, but it is the same result checked or unchecked. Isset not working properly either.
<input type="checkbox" value="Agree" id="siteAgreement">
if(!isset($siteAgreement) || !$siteAgreement || $siteAgreement != "Agree"){
//////Unchecked
}
Change
siteAgreement = $("#siteAgreement").value;
to something like this:
siteAgreement = $("#siteAgreement").is(':checked') ? $("#siteAgreement").val() : null;
But you should also add the name attribute so browsers with javascript turned off can also use your site.
Also you can use some code that generates request automatically from form (something like jquery.form), so you don't have to update javascript whenever you change the form.
Example here: http://jsfiddle.net/RhasK/
Here try this:
if(!isset($_POST['siteAgreement']) || !$_POST['siteAgreement'] || $_POST['siteAgreement'] != "Agree"){
//////Unchecked
}
Unless you're extracting the variable before, $siteAgreement won't be set. You can use $_POST['nameofelement'] to access the data.
if($_POST["siteAgreement"] !== "Agree") {
//not checked
}
will work fine
you should only need to check if it is set or not.
if(!isset($_POST['siteAgreement'])){
//then it is unchecked
}
Also, you didn't give your input a name. You need to put...
<input type="checkbox" name="siteAgreement" value="Agree" id="siteAgreement">
You need a name to access it in PHP.
Related
I am using checkboxes in my form to allow the user to turn on/off certain settings. I load the form by providing the correct 'state' from values returned from the db. They can then change these and submit the form where it is processed. Example...
<input type="checkbox" name="settings[something]" '.($settings[one] == 1 ? 'value="1" checked' : 'unchecked').'/>
<input type="checkbox" name="settings[somethingelse]" '.($settings[one] == 1 ? 'value="1" checked' : 'unchecked').'/>
... and so on...
On the receiving end is where I can't seem to come up with a good solution to handle these.
If any of these are unchecked then the value is not even sent. If it is checked then a value of '1'.
So, other than doing something like :
$something = $_POST['settings'][something']
$somethingelse = $_POST['settings'][somethingelse']
... and so on
if (!$something == 1)
{
$something = null;
}
... and so on
for each value I am expecting... is there an easier way I am missing here? I have to check each value whether it was sent or not because I am also including an option to set these values as default for multiple rows in my db - not just the one they are editing.
EDIT :
I took some time to think about this. In my database I am storing these as 1 or 0 values. Rather than checking if they were posted (set) on the receiving end of the form I am going to check if they are != to 1. I can run down the list of values and everything that is not equal to 1 is set to 0. This way I have a full list of all values to update in the db AND I am verifying the data integrity before inserting it into the database (1 or 0).
I am now trying to think of a quicker way to run through my 'list' to check rather than an if statement for each. Going to play around with some arrays and see what I can come up with.
Checkboxes are a bit special as they are not sent to the server when they are not checked.
So the best way to check for a checkbox, is not by it's value, but simply by checking if it is set:
if (isset($_POST['settings']['something']))
{
// Do what you need to do
}
else
{
// The checkbox was not on the form (you should know that already) OR unchecked
}
While trying to handle image maps, I get an error if I try to retrieve the coordinates via $_POST . I do not understand the reason though.
For the following form :
<form method='post' action='action_script.php'>
<input name='coordinates' type='image' src='./rabbits.jpg' />
</form>
this is the action_script.php script :
<?php
echo "Coordinates : {$_POST['coordinates_x']} and {$_POST['coordinates_y']} ";
This script throws an error,saying coordinates_x and coordinates_y are undefined. But if I replace $_POST with $_REQUEST it works fine and tells the coordinates. Why do I get an error when I use $_POST ?
The following script doesn't produce an error :
<?php
echo "Coordinates: {$_REQUEST['coordinates_x']} and {$_REQUEST['coordinates_y']}";
Is that your full code? You don't seem to be showing us the submit button etc.
But what matters is that you are ASSUMING that everything went well and was posted, never assume anything, use the arbitrary operator to actually check if anything was posted:
$xCord = isset($_POST['coordinates_x']) ? $_POST['coordinates_x'] : false;
$yCord = isset($_POST['coordinates_x']) ? $_POST['coordinates_x'] : false;
And, like pointed out, you should really be doing something like
$xCord = isset($_POST['coordinates']) ? $_POST['coordinates'] : false;
And if It's really something that you can strip down then this shouldn't ruin the data.
Now you can actually check if it was successfully posted, it it turns out that It's false then you're simply doing something wrong.
Now It makes sense to echo
echo "Coordinates: $xCord and $yCord";
But then again, I find your form a little funky. Try this new approach and give us the full code.
I have several input fields and I want it to submit when there is only one field with entered values and the others are empty (updating user data). I worked by now with isset() but this only sends the form when every field is filledout:
if (isset
($_POST['submit']) AND
($_POST['firstname']) AND
($_POST['lastname']) AND
($_POST['address']) AND
($_POST['ZIP']) AND
($_POST['phonenumber']) AND
($_POST['mail']) AND
($_POST['group'])
)
Later on I check in the mail template (another file) if there is a value and wheter to show it in the mail or not:
{if !empty($firstname)}{translate text='First Name'}: {$firstname|escape} {/if}
Is my idea ok or is there an easier way to solve this?
The first if statement is in conflict with your requirements; you are requiring all fields to be filled in by using the AND operation - use OR and it will work with any single field value.
Validation should/could also be performed on the page itself by using javascript as Matt recommends.
To ensure that only one field is set do the following you could count the number of entries in _POST
if(count($_POST) == 1 AND
(isset($_POST['submit']) OR
isset($_POST['firstname']) OR
isset($_POST['lastname']) OR
isset($_POST['address']) OR
isset($_POST['ZIP']) OR
isset($_POST['phonenumber']) OR
isset($_POST['mail']) OR
isset($_POST['group'])
))
Either way it's not a very elegant way of doing this - but it will work.
If you want only one value from a field which is set to required (if possible, use javascript, or HTML5 has a required attribute for that), simply ignore other values from other fields:
<?php
if ( isset( $_POST['submit'] ) ) {
$wanted_value = addslashes( strip_tags( $_POST['input_name'] ) );
// preventing from sql injection
// ignore other values
// and start manipulating it
}
?>
One suggestion would to be to use javascript and your onSubmit function on the form in addition to a serverside check. Using that, you can check all of your fields, and alert the user to fill some in BEFORE it gets submitted to the server.
In a javascript function check all of your inputs for a correct input, and allow the data to be sent to the server if it is all filled in correctly, or pop up an alert saying what else needs to be done before it can be submitted.
Doing this check strictly serverside will require a server request to check the input every time, as opposed to having the client check it, and submit it only if everything is correct.
Assuming you want to send the form if there's at least one field that's filled, you could use the following if-statement:
if(count($_POST) > 1)
This allows you to submit the form and have at least one field filled, but you can also have more fields filled.
If you want to send the form only if there's one field that's filled, you could change the above if-statement to the following:
if(count($_POST) == 2)
This allows you to have only one field filled.
The reason I use "== 2" is because the submit-button is also something that will be sent.
If you want to allow all the fields to be empty, you can use the following if-statement:
if(count($_POST) > 0)
This would allow you to submit the button and leave all the other fields empty.
The reason this works is because $_POST is a pre-defined array-variable.
To ensure that the user only uses fields that you want them to use and still keep the code clean, you can use an array.
Do the following:
$allowed_fields = array('firstname','lastname','address','ZIP','phonenumber','mail','group');
And then just add the following to your if-statement:
if(count($_POST) == 2 AND in_array($allowed_fields, $_POST))
Although I visit php documentation , I didn't understand usage of "isset" function .
1 - for example in a php tutorial book author wrote a text with this context : when we create a form in a first.html and we want to use from form information in second.php , we must use these 2 pieces of code :
if(!isset($_GET['q']))
die("The Search key word is not set !!!");
$key = $_GET['q'];
if($key == "")
die("The Search key word must be entered !!!");
but I don't understand what is difference between these 2 codes ?
2 - for another example I saw this code for checking that a bottom is clicked or not :
if(isset($_POST['login_btn']))
{
....
}
but I don't understand why does it check that a bottom is clicked or not ?
$key="";
isset($key) //This evaluates to true.
The string is empty, but the variable is defined. The isset() function returns true, even for an empty string.
Perhaps you would like to use empty() instead, which has a broader range of conditions that evaluate to false.
isset checks to see if a given variable or index exists. If you assume that a variable exists and it doesn't, PHP generates a notice. All you're doing by using isset is suppressing possible notices -- which is good practice.
The difference is, in one instance the form was not submitted, in the second instance, the form was submitted, but with a blank value.
You wouldn't want to process a form on your page if the form has not been submitted yet.
There may also be multiple forms on one page, so you might check the button value to find out which form was submitted.
This function is quite simple
As on php.net:
Determine if a variable is set and is not NULL.
In your case, the isset function checks of your post variable is empty or not
$key == ""; // Is $key an empty string
isset($key); // Has the $key variable been defined and not null
And just for reference, here are a few others that may be useful
empty($key); // Is $key and empty value (0, false, null, "", array())
$key == false // Is $key a falsey value (0, false, null, "", "0", array())
$key === false // Is $key a false boolean (false)
I'm just going to dissect your code a little bit..
isset
if(!isset($_GET['q']))
die("The Search key word is not set !!!");
Would typically be used to see if a variable in a URL is set so something like this:
http://mysite.com/index.php?q=1
Would have $_GET['q'] set and isset($_GET['q']) would come back true
$key==""
$key = $_GET['q'];
if($key == "")
Would check to see if $key is empty. Using my previous example URL, $key would not be empty or blank, it would be 1.
Why check for a button press
The script that processes your form needs to know that it is being accessed after the form that way it does not error out. This is where you would want to make sure that the form submit button was pressed. As this is confusing, here is an example:
Say you want to insert a tag for your blogging system into a database you might have code that looks like this:
AddTag.php
<form name="addtag" method="process.php" action="post">
<input type="text" name="tagname" />
<input type="submit" name="submittag" />
</form>
process.php
<?php
if ($_POST['submittag']) {
//INSERT query
}
?>
As you can see, if process.php is accessed without the AddTag form being accessed first, the script would not try to insert your tag.
Everyone here has already explained to you what the isset() function checks for (that being if a variable is set or not), but I think what you're really asking about is how $_GET[] and $_POST[] work. You're going to need to look more at the form that feeds this code. Read about what $_GET[] and $_POST[] variables are and I think this code will make a lot more sense to you.
For instance, your second example checks to see if the value named login_btn was sent via post method. If it was, then it runs the ... code block.
I have this code to check that my ToS checkbox is checked:
if (!isset($_POST['tosagree'])) {//if the user did not agree to ToS
$errors[] = '<span>Please agree to the Terms of Service.<span>';
}
For some reason it is allowing me to register even with that code there. The weird thing is that if any other field is not field and that field is not checked it will print the error, but if that is the only problem it allows the user to register.
Update: seems like its a problem with something weird in my code. If you feel like looking through 217 lines of code here is all the code: http://pastebin.com/YkERYpeF
Whether !isset($_POST['tosagree']) will be enough depends on the browser.
To be safe, always set the value attribute of the checkbox. Then, you simply check if that value is present:
<input type='checkbox' value='agreed'/>
Then do this:
if (!isset($_POST['tosagree']) || $_POST['tosagree'] != "agreed" ) {
$errors[] = '<span>Please agree to the Terms of Service.<span>';
}
Also, when the value attribute is not explicitly specified, browsers will usually set value to On when it is checked.
Edit
Ok, I know what's happening. In your PHP code, you have this block:
if (!isset($_POST['tosagree']) || $_POST['tosagree'] != "agreed") {//if the user did not agree to ToS
$errors[] = '<span>Please agree to the Terms of Service.<span>';
}
Then later you have this line:
if ($un && $e && $p && $ic) { //if there are no errors
The problem is that you don't have a flag for when the TOS checkbox isn't checked. The error can't be printed because in the if statement you have a call to exit().