Jump to content

Recommended Posts

5 hours ago, Barand said:

a <button> element can have a value attribute independent of its label

True. This would solve the issue. I want to say (though to be honest I'm not entirely confident in my memory so don't quote me) that some browsers have issues passing button and submit element attributes on submission? Like if you name your submit button and then check for that index in the $_POST array being set it doesn't always catch it - I want to say it's mostly IE, which probably doesn't really matter any more anyway.

@SaranacLake The reason your third form results are off is that both the buttons have the same name, and they're both submitted with the form. So the value of `which_choice_did_i_make` is overwritten and will always be 'Form4_Input2'. The thing about it is, if you're using AJAX and JavaScript you can easily use one form - the onClick event tells the JS event handler which button was clicked, that information is put into the data array and passed to the PHP script. No hidden fields, one form, no page refresh necessary. However, the way you're doing it, there's no way the hidden field can tell the PHP script which button was clicked - all the data is always submitted. Just the act of clicking an HTML button doesn't trigger any special actions that will bind a field value to a field (obviously this can be done with JavaScript, but it won't happen in plain old HTML).

Assuming my memory is as bad as it seems to be these days, Barand's suggestion is the way to go for you - check the value of the button element name in $_POST and go from there. This allows you to have one form, no hidden fields,  with mandatory page refresh.

  • Like 1
10 hours ago, SaranacLake said:

then as long as you didn't need to compare values, I guess that works.

Correct. With buttons (other form values are different), I've never had the need to use the "value" portion of a button in my PHP processing. For me, the "value" is simply what's displayed to the visitor. In fact, if you completely leave out the value (like this: <input type="submit" name="movies">), your browser will give it a default name of "Submit" to the visitor.

 

10 hours ago, SaranacLake said:

So if you have 4 INPUTs ... as long as you didn't need to compare values, I guess that works.

Correct.

 

10 hours ago, SaranacLake said:

True, but if NAME=MEMBERSHIP_TYPE then your approach wouldn't work if the VALUES={Silver,Gold,Platinum}

I'm assuming you have 3 buttons. Right?
If so, the Silver Member will click the silver membership button (<input type="submit" name="silver_member" value="click me if you are silver">
... and a Platinum member will click the platinum button (<input type="submit" name="platinum" value="Platinum Members Only">
...etc.

If your page is more complex, and you have ONE page, with ONE button, then the page would have to already "know" if the member is gold plat or silver.

<?php
session_start();
if ($_SESSION["membership"] == 'platinum'){
$button = '<input type="submit" name="platinum_content" value="click me">';
} elseif ($_SESSION["membership"] == 'gold') {
$button = '<input type="submit" name="gold_content" value="click me">';
} elseif ($_SESSION["membership"] == 'silver') {
$button = '<input type="submit" name="silver_stuff" value="click me">';
} else {
$button = '<input type="submit" name="not_a_member" value="Click Here To Learn More">';
}

echo '<html><body>';
echo 'Hey buddy, click here<BR>';
echo $button;
echo '</body></html>';
?>

.... something like that. You get the idea.

 

 

5 hours ago, Barand said:

If it helps, note that that a <button> element can have a value attribute independent of its label

That is cool! I noticed this fact just yesterday when I was examining the "Submit Reply" button on this site's page.
The internet is advancing too fast for me :-)

1 hour ago, maxxd said:

I want to say (though to be honest I'm not entirely confident in my memory so don't quote me) that some browsers have issues passing button and submit element attributes on submission? Like if you name your submit button and then check for that index in the $_POST array being set it doesn't always catch it - I want to say it's mostly IE, which probably doesn't really matter any more anyway.

Afaik, this is no longer an issue in any modern browser. 

This was an issue back the the old days, but was only an issue via implicit submit (via Enter in a text field). If you hit enter in a text field to submit the form some browsers would not include the submit button name/value where as others would.  I forget which browser did which action.   Fun fact, google actually used to detect if the button name was submitted and show a "Tip: You can just hit enter to search" bit on the results page.

I believe old IE also had issues with <button> specifically, ignoring the value attribute and passing it's label content instead at times.  As such, it was best to give the buttons different names and check for that instead of the values.

These days however, there's no problem with just providing several buttons with the same name and different values.  The browser will submit the value of the button you clicked on and you can detect that in your script just fine.  If your form has other fields, then what happens on the implicit submit is now clearly defined in the spec.

 

  • Like 1
3 hours ago, maxxd said:

True. This would solve the issue. I want to say (though to be honest I'm not entirely confident in my memory so don't quote me) that some browsers have issues passing button and submit element attributes on submission? Like if you name your submit button and then check for that index in the $_POST array being set it doesn't always catch it - I want to say it's mostly IE, which probably doesn't really matter any more anyway.

@Barand and @maxxd,

I haven't actively coded PHP in nearly 5 years - which is a painful place since I am trying to finish the last 10% of a very complex code-base.  😞

I added a var_dump to Barand's code to try and undrstand what was going on, but it isn't working.

What did I do wrong?

	<?php
    var_dump($_POST);        // Added to show data associated with button click.
    
    $option = $_POST['option'] ?? '';
    if ($option) echo "You chose $option<hr>";
 ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Sample</title>
</head>
<body>
    <form>
        Select an option
        <button name="option" value="1">Choose me</button>
        <button name="option" value="2">Choose me</button>
        <button name="option" value="3">No, Choose me</button>
        <button name="option" value="4">No, Choose me</button>
        <button name="option" value="5">No, Choose me</button>
    </form>
</body>
</html>
	

 

 

3 hours ago, maxxd said:

@SaranacLake The reason your third form results are off is that both the buttons have the same name, and they're both submitted with the form. So the value of `which_choice_did_i_make` is overwritten and will always be 'Form4_Input2'.

Yeah, I came to that conclusion last night.

(This is probably why on a related page that I started working on a while back I broke things up into 3 forms on one web page.)

 

3 hours ago, maxxd said:

The thing about it is, if you're using AJAX and JavaScript you can easily use one form - the onClick event tells the JS event handler which button was clicked, that information is put into the data array and passed to the PHP script. No hidden fields, one form, no page refresh necessary.

However, the way you're doing it, there's no way the hidden field can tell the PHP script which button was clicked - all the data is always submitted. Just the act of clicking an HTML button doesn't trigger any special actions that will bind a field value to a field (obviously this can be done with JavaScript, but it won't happen in plain old HTML).

Yeah, that's a bummer.

 

3 hours ago, maxxd said:

Assuming my memory is as bad as it seems to be these days, Barand's suggestion is the way to go for you - check the value of the button element name in $_POST and go from there. This allows you to have one form, no hidden fields,  with mandatory page refresh.

Okay, but why didn't my var_dump work?

 

You'll have to define "isn't working". The following works for me as expected:

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
	print("<pre>".var_export($_POST, true)."</pre>");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Testing</title>
</head>
<body>

	<form method="post" name="firstForm">
		<button id="whatever" name="click" value="button_1">Click Me!</button>
		<button id="whatever2" name="click" value="button_2">Click Me, Too!</button>
	</form>

</body>
</html>

 

@maxxd

 

20 minutes ago, maxxd said:

You'll have to define "isn't working". The following works for me as expected:

My var_dump isn't displaying anything.

 

Then I rewrite my code, tried this, but when I click on a button I don't get any results...

	<?php
    if ($_SERVER['REQUEST_METHOD']=='POST'){
        // My code...
        var_dump($_POST);
    
        // Maxxd's code...
        $option = $_POST['option'] ?? '';
        if ($option) echo "You chose $option<hr>";
    }
 ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Sample</title>
</head>
<body>
    <form>
        Select an option
        <button name="option" value="1">Choose me</button>
        <button name="option" value="2">Choose me</button>
        <button name="option" value="3">No, Choose me</button>
        <button name="option" value="4">No, Choose me</button>
        <button name="option" value="5">No, Choose me</button>
    </form>
</body>
</html>
	

 

 

Edited by SaranacLake
9 minutes ago, maxxd said:

Specify the method in your form tag (method="post").

@maxxd

Told you I was rusty on things!! :facepalm:

 

So there is still a lot of application logic I have to figure out, but it sounds like upgrading to the HTML5 button tag should help me to address any situations where I need to have several command-type buttons on one web page, right?

And another advantage is now I can just have one form, right?

 

Edited by SaranacLake
8 hours ago, maxxd said:

print("<pre>".var_export($_POST, true)."</pre>");

That is a new one for me - I didn't know there is a one-liner to see post values.

I regularly use the following line of code almost all the time when I am debugging pages with a lot of inputs:
print '<pre>';foreach($_POST as $var=>$val){ echo "$var......$val<BR>"; } print '</pre>';

I put it all on one line so I can "turn it off" with a hashmark # to the left.

It gives me a nice itemized column. I don't have to strain my eyes or think too hard to see what variables and values were posted.

And, if you change $_POST to $_REQUEST, it will show all <form method="GET"> variables as well (if you use get variables).

<form> without a method="post" directive will default to "GET" ("GET" is where the url window of your browser will show all the variables and their values, like
www.example.com/index.php?weekday=today&user=beginner&status=king&month=december

Regarding HTML5, yes you can actually dictate what form each button uses..... but again, I'm not a fan of complexity. I ended up almost using HTML5 buttons on a page that would have had 2 forms, but I rewrote my code to keep it simple, using only one form per page.

Edited by StevenOliver
14 hours ago, StevenOliver said:

I regularly use the following line of code almost all the time when I am debugging pages with a lot of inputs

If you use it regularly, you should just wrap it up in a function that you can call.  I used a function like this often in my earlier days.

function dv(/*...*/){
    if (!defined('ENABLE_DEBUG') || !ENABLE_DEBUG){
        return;
    }

    echo '<pre>';
    for ($i = 0, $len = func_num_args(); $i < $len; $i++){
        var_dump(func_get_arg($i));
        echo "\r\n";
    }
    echo '</pre>';
}                                                  

Then if I wanted to dump some variables I could just dv($_POST, $_GET); for example.    The check for ENABLE_DEBUG is there so that if by chance any calls got left in the code they would do nothing on the production site as I only setup that constant on my development system.

These days I just use Xdebug with breakpoints which is much nicer and easier.  Xdebug will also change var_dump to be readable without the <pre> tags so such an extra functions isn't really necessary.

 

5 hours ago, kicken said:

These days I just use Xdebug with breakpoints which is much nicer and easier.

For the life of me I've not been able to get XDebug working with VSCode and my Docker containers, so I'm deeply jealous of your setup.

Kicken, thank you for the suggestion. It would be embarrassing for me to say I am very rusty on how to create functions. So I will use the function that you wrote.

Speaking of functions, I'm trying to learn jQuery.... and when I see examples on how to do things via jQuery, they are always the 2 or 3 lines without the function wrapper..... and I don't know how to make a function 'wrapper' that I can call, like I do with Javascript :-) And, as far as PHP functions, I'm still trying to figure out why "return" is sometimes written on the last line (the functions always work without the word "return" at the end  :-)  (see how rusty I am :-)

I'll also check out Xdebug.

Thank you again!!

7 hours ago, StevenOliver said:

I'm still trying to figure out why "return" is sometimes written on the last line (the functions always work without the word "return" at the end 

Where you have a function that desn't return a value (referred to in some languages as a void function and in other languages as a procedure) then, I agree, a return on the last line is pointless as it exits the function anyway.

For functions that return a value, a return is necessary, and usually on the last line, although not necessarily.

Another debugging tip...

  • When outputting to the screen normally, use "echo"
  • When outputting variables for debug puposes only, use "print".

This makes it easy to search and remove stuff that shouldn't be in the production version.

Barand, thank you! And, thank you for the debugging tip. I've been using echo and print interchangeably. I like your idea.

So..... Guess what I did this morning! I got a copy of O'Reilly's "Learning PHP," and I'm starting from the very very beginning. One page at a time. I just now learned that "echo" and "print" don't have to be lowercase. Seriously, I'm not kidding. I'm starting from the very beginning. I'm going to actually learn PHP!

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.