Determine if empty $_POST submitted - php

I have a form containing tabular data, with each row having a checkbox with the same name so that it gets passed via POST as an array to a PHP page. Everything work fine, but I have an issue relating to when none of the items on the page are selected - this is a special case that I need to handle in a specific way, but I am trying to figure out how to determine the best way to tell when this condition occurs, as when it does the $_POST array is completely empty.
Any strategies to help in determining when an empty set of data has been POSTed to a page in PHP?

Use the empty function
if( empty($_POST) ) {
//do empty $_POST stuff here
}

Add a hidden input field to the page with a known value. This field will always be passed in with the POST data, therefore you will know that the user landed via form submission rather than direct URL. It's as simple as:-
<input type='hidden' name='posted' value='true'>

You can accomplish this a few different ways.
//Method 1
if($_POST) {
//Do Stuff
}
//Method 2
if(!empty($_POST)) {
//Do Stuff
}
//Method 3 - For detecting if a form was submitted
<input type="submit" name="submit" />
if(sizeof($_POST)>1) {
//Do Stuff
}
Method 2 will fail if your value is 0, for a checkbox you need not worry though.
Method 3 relies on you giving your submit button a name, so it is at least submitted when nothing is checked. Then you can see if sizeof() returns more than 1 to see if anything was checked.
DEMO: http://wecodesign.com/demos/stackoverflow-7424062.php

I think you've answered your own question. If the $_POST array is empty then there are no checked checkboxes.

<form>
<input type="text" name="user" value="" />
<input type="submit" name="post" value="Save" />
</form>
//php
if (isset($_POST['post']))
{
//code here
}

if ( !empty( $_POST["field"] ) ) {
// Field sent
} else {
// Field empty
}

(count($_POST) == 0) //returns boolean
or do you mean when the form is posted but no information is entered?

Post data is available when a form is submitted. Given the following:
if($_POST)
{
// Bar
}
// Foo
If the form is not submitted Foo will be performed.
If the form is submitted Bar will be performed and then Foo.
Given the following:
if ($_POST)
{
// Bar
}
else
{
// Foo
}
If the form is not submitted Foo will be performed.
If the form is submitted Bar will be performed.
As for your other question, checking for empty or appropriate data is basic server-side form validation. If you use a library that can be as simple as:
if ($_POST)
{
$form_helper = new FormHelper();
$form_helper->validate($_POST["email"], "email");
$form_helper->validate($_POST["password"], "password");
if (! $form_helper->notifications())
{
// Bar
}
}
For your specific case (and without a library) it might be:
if ($_POST)
{
if (empty($_POST["checklist"])
{
// Delete all entries.
}
else
{
// Do something else.
}
// Foo
}

This will check if any form values have been entered - assuming default input value = ''
$post = array_filter($_POST,'strlen'); //filter all empty values
//if html input submit button has NO name value
if (sizeof($post)):
//Do stuff
endif;
// OR if html input submit button HAS a name value
if (sizeof($post) > 1):
//Do stuff
endif;
You could use a callback function if exact filtering was required
$post = array_filter($_POST,function ($k){ return $k != '' || $k != 'my default value' || *some other condition etc etc* ; });

Related

Javascript to check for form data does not work

I have the following code to check for form data and I can't figure out why its not working.
<script type="text/javascript">
function checkStuff() {
// By default, we plan to submit the form.
var formOkay = 1;
// Check to see if field_1 has a value. If not, we note that by changing our variable.
if(document.getElementById('requestorfirstname').value == '')
formOkay = 0;
// Let the user know something is wrong somehow. An alert is easiest.
alert('Requestor Name Required!');
// If you return true the form will submit. If you return false it will not.
if(formOkay == 1) {
return true;
} else {
return false;
}
}
</script>
Now here is the html form piece its checking onsubmit.
<input type="text" name="requestorfirstname" />
Thanks for the help!
document.getElementById looks for elements by ID. Your field doesn't have an ID, it has a NAME.
document.getElementById selects an element by id, not by name.
Some ways to solve the problem:
Add id="requestorfirstname" to the input element.
Use document.getElementsByName('requestorfirstname')[0]. getElementsByName returns a list, hence [0].
Use the document.querySelector('[name="requestorfirstname"]') method.
Get a reference to the form, and access the element using the .elements collection.For example, if your page has only one form:
document.forms[0].elements['requestorfirstname']
A name attribute on an HTML element is NOT the same as an id. You have no id on your input field, so there's no way for getElementById to find it. Change the element to:
<input type="text" name="requestorfirstname" id="requestorfirstname" />
^^^^^^^^^^^^^^^^^^^^^^^^ - add this

How can I check a input field exists in the form when I submit it to the server?

How can I check a input field exists in the form when I submit it to the server?
For instance, I want to check whether a check box named 'mem_follow' exists or not in the form.
Or do I have to use javascript (jquery)?
I'm guessing you need to check on the server side after the form is submitted. If that's the case, you can check like so...
<?php
if (isset($_POST['mem_follow']))
{
// Work your server side magic here
} else {
// The field was not present, so react accordingly
}
?>
Hope this helps!
It'd HAVE to be Javascript. PHP can't reach out from the server into the browser's guts and check for you. It could only check if the fieldname is present in the submitted data.
In jquery it's trivial:
if ($('input[name="nameoffield"]')) { ... field exists ... }
Of course, this raises the question... why do you need to know if a field exists or not? Presumably you're the one who's built the form. You should know already if the field exists or not.
In the following script the form will not submit unless the checkbox is ticked. And If you do try, the hidden div with an error message is shown, to let you know why.
<form action="test.php" method="post" id="myform">
<input type="checkbox" name="checkbox" id="checkbox" value="YES" />
<input type="submit" name="submit" value="submit" />
</form>
<div id="error_message_div" style="display:none">You must tick the checkbox</div>
<script>
$('#myform').submit(function() {
if($('#checkbox').attr('checked')) {
return true;
} else {
$("#error_message_div").show();
return false;
}
});
</script>
Cheers
Matt
you can do this in two way:
By Server Side: In php
<?php
if (isset($_POST['mem_follow'])
{
// Work your server side magic here
} else {
// The field was not present, so react accordingly
}
?>
By Client side: In Jquery
$('#submit_button').click(function() {
if ($('input[name="box_name"]')) {
if($('input[name="box_name"]').attr('checked')) {
return true;
} else {
return false;
}
}
});
You can use jQuery and do something like this:
$('#myForm').submit(function (e) {
if($(this).children(':checkbox[name=mem_follow]').length > 0)
//exists
else
//doesn't exist
});
Or use php and check if there is any variable named 'mem_follow': (this is for POST, although it doesn't matter if it's GET or POST)
if(isset($_POST['mem_follow']))
//exists
else
//doesn't exist
You can try this code in the form submit event handler
if($("input[name=mem_follow]").length > 0){
//It exists
}
The other answers here are correct: you'd have to do that on the client side. In the case of a checkbox input field, if the box is not checked there is no guarantee the browser will include a POST parameter for that field.
For example, if you submit this form without checking the checkbox:
<form action="test.php" method="post">
<input type="checkbox" name="checkbox" value="YES" />
<input type="submit" name="submit" value="submit" />
</form>
only the submit=submit parameter will be submitted.
So, no, you cannot guarantee that a given checkbox exists in a form on the server side.
well for all elements try this
number = document.form_name.elements.length;
else for a specific name of input use this
number = document.form_name.getElementsBYName('Name of Input').length;
Thats it
enjoy
I suggest you to use Jquery
$.fn.Exists = function() {
return $(this).length>0;
}
if ($("here are your selector to check").Exists()) {
...
}
Simple and useful!
And you can use this Exists method everywhere))))
You can use javascript (or jQuery) to do that :
<script>
$('#myform').submit(function() {
if($('#yourFieldId').val()=='') {
alert('the field ' + $('#yourformField').name() + ' is empty !');
return false;
} else {
return true;
}
});
</script>
you can do this for all your fields one by one, or by putting all conditions in the if statement.

help storing postdata with codeigniter

Here is my scenario, I am creating a form with codeigniter, I understand how to populate the fields with models and such. I have the layout of the form. It is now running from my index function. I want to store all the data given to that form and access them in a postdata array with each index being the name of the value. Please help. CodeIgniter, PHP
you create the form
echo form_open('mycontroller/mymethod');
// rest of form functions
or <form name="myform" method="post" action="<?php echo site_url('mycontroler/mymethod');?>" > // rest of html form
then, in Mycontroller:
function mymethod()
{
$postarray = $this->input->post();
// you can pass it to a model to do the elaboration , see below
$this->myloadedmodel->elaborate_form($postarray)
}
Model:
function elaborate_form($postarray)
{
foreach($postarray as $field)
{
\\ do your stuff
}
}
If you want XSS filtering you can pass a TRUE as second parameter in the $this->input->post() call. Check user guide on input library
See code igniter's input class
One exemple of how to form your code would be:
public function add_something()
{
if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') { // if the form was submitted
$form = $this->input->post();
// <input name="field1" value="value1 ... => $form['field1'] = 'value1'
// you should do some checks here on the fields to make sure they each fits what you were expecting (validation, filtering ...)
// deal with your $form array, for exemple insert the content in the database
if ($it_worked) {
// redirect to the next page, so that F5/reload won't cause a resubmit
header('Location: next.php');
exit; // make sure it stops here
}
// something went wrong, add whatever you need to your view so they can display the error status on the form
}
// display the form
}
This way your form will be displayed and if submitted its content will be processed, if an error occurs you will be able to keep the submitted values to pre-enter them in the form, display an error message etc ... And if it works the user is redirected to that he can reload the page safely without submitting multiple times.

losing variables from javascript array when passing to php

I'm trying to implement a page with a choice of user's preferences in an HTML form where if the checkbox ALL is selected then all sub-checkbox base1, base2 and base3 are checked automatically, and if any of sub-checkboxes is un-selected then the checkbox ALL must be unchecked. I used a javascript function which works but when I submit the form only the last variable in the array of checkboxes is sent.
<SCRIPT LANGUAGE="JavaScript">
function checkChoice(field, i) {
if (i == 0) { // "All" checkbox selected.
if(field[0].checked==true) {
for (i = 1; i < field.length; i++)
field[i].checked = true;
}
}
else {
if (field[i].checked == false) {
field[0].checked = false;
}
}
}
<form name="form" method = "POST" action="preferences.php">
<input type=checkbox name=classes1 value="allbases" onclick="checkChoice(document.form.classes1, 0)">All bases
</td><td>
<input type=checkbox name=classes1 value="base1" onclick="checkChoice(document.form.classes1, 1)">Base1
<br>
<input type=checkbox name=classes1 value="base2" onclick="checkChoice(document.form.classes1, 2)">Base2
<br>
<input type=checkbox name=classes1 value="base3" onclick="checkChoice(document.form.classes1, 3)">Base3
<input type="submit" value="Set preferences" >
If I call the checkboxes'names in "classes1[]" all the values are submited but the javascript function doesn't work anymore. Is there a way of fixing this?
Thanks for any help.
For an alternative of checkChoice: check this SO question and the jsfiddle I presented there.
[edit] concerning your comment: a bit of extra thinking would have brought you to this solution
All of the values actually ARE submitted but PHP will overwrite $_POST['classes1'] each time until you are just left with the last value. If however you add '[]' to your input names then they are added to an array.
Since the latter causes a problem with javascript, can you not just either
a) iterate all of the form elements from the form.elements array,
or b) give each input a unique id and use document.getElementById() to find it?

how to eliminate space in forms in php

how can i prevent a form to be submitted when it only contains a space? for example a user presses the space bar on a field, the space will be considered as a character so the forms submits. how can i prevent that in php?
For PHP - Server-side validation (After the form is submitted)
A combination of trim() and empty() will return true if passed a string with only a space.
$a = ' ';
$a = trim($a);
if (empty($a)) print 'Empty!'; // Empty!
Sidenote: Under normal circumstances, it's always a good idea to trim() user-input.
For Javascript - Client-side validation (Before the form is submitted)
Use the onSubmit event to fire a validate function:
<form onSubmit="validate()">
<input type="text" id="myInput" />
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
function validate() {
myInput = document.getElementById('myInput');
if (myInput.value.match(/^s+$/) || myInput.value == '') {
alert('No Empty Values!');
return false;
}
}
</script>
Use trim() and then test against null values.
Mike B presents a good point. You could prevent the form from actually being submitted with Javascript. If you rely on PHP, the form will be submitted, but you could present the same form to the user with an error message.
HTML:
<form onsubmit="return validate(this);">
Javascript:
function validate(form) {
ok = true;
for (var i = 0, il = form.elements.length; i < il; ++i) {
form.elements[i].value = form.elements[i].value
.replace(/^\s\s*/, '')
.replace(/\s\s*$/, '');
ok &= !!form.elements[i].value;
}
if (!ok) alert("Oh hey - type something in these boxes, k?");
return ok;
}
PHP:
$myVar = trim($_POST['myFormVariable']);
if (!$myVar) {
echo "Oh hey, you should type something.";
} else {
doStuff();
}
Once your forms get more complex Jquery has a wonderful plugin for this called validate that provides extensive form validation.
+1 to Plan B. Always validate the same input again in php as there is nothing stopping a user from just creating his own form and submitting it to your page.

Categories