Page 1 of 1

Way to check if submit button/s haven't been clicked

Posted: Tue Feb 19, 2013 4:33 am
by social_experiment
I have a form with two submit buttons and i know how to check whether the buttons have been clicked; but how do you check if neither of the buttons have been clicked ?

The page will have two different functions depending on the button clicked and for no button clicked a message will be displayed. I did a var_dump($_POST) on the page if no button is clicked and i get this result:

Code: Select all

array(0) { } 
My thinking, when determining whether a button has been clicked, is to start with this code:

Code: Select all

 // 
 if (count($_POST) == 0) {
   /*
    default message if page is accessed directly
   */
  } 
  else {
   /*
    check which button has been clicked.
   */
  }
In the else statement i'll have two if statements, each one checking for the click of a button.

Is this a valid approach? There might be additional functions for this page in future so i want the code to be as flexible as possible.

Re: Way to check if submit button/s haven't been clicked

Posted: Tue Feb 19, 2013 5:11 am
by s.dot
How can a form be posted if it hasn't been submitted? Do you mean like if it's not a click and the user hits the enter button instead?

Otherwise the code you just have is basically this:

Code: Select all

if (empty($_POST))
{
    //nothing to do here, page is accessed directly with no post
} else
{
    //there's post data
    //if (!empty($_POST['submit']) && $_POST['submit'] == 'choice1')){ .. }
    //if (!empty($_POST['submit']) && $_POST['submit'] == 'choice2')){ .. }
    //etc
}
It is a valid approach, yes. This is normal procedure for processing forms on a page. A bit more flexible approach would be looking at the post-redirect-get pattern to avoid user refreshing their browser and resubmitting the data.

Re: Way to check if submit button/s haven't been clicked

Posted: Tue Feb 19, 2013 6:26 am
by social_experiment
thanks for the reply
s.dot wrote:Do you mean like if it's not a click and the user hits the enter button instead?
it's more about accessing a page via url;

the use of empty() looks like a better option than using count(); thanks for the hint :)

Re: Way to check if submit button/s haven't been clicked

Posted: Tue Feb 19, 2013 3:16 pm
by Christopher
You can check if($_SERVER['REQUEST_METHOD'] == 'POST'). You could also add something like <input type="hidden" name="submitted" value="yes"/> to the form. Those give you more things to positively check for.

Re: Way to check if submit button/s haven't been clicked

Posted: Tue Feb 19, 2013 3:23 pm
by social_experiment
:) thanks for the tip Christopher

Re: Way to check if submit button/s haven't been clicked

Posted: Tue Feb 19, 2013 8:12 pm
by s.dot
Another tip is to display the form BELOW the processing (use !empty).. reverse order as above. This way you can show errors on the form if there's an error.