Creating Buttons: Take 1


Another control you'll see often in web pages is the HTML button. Buttons are different from other controls, however, because when clicked, they don't stay clicked, which means that when the form is sent to your script, the button has long since popped up. So how do you determine which button the user clicked from PHP? One way is with a mix of JavaScript and a hidden control, as shown in phpbuttons.html, Example 5-19. When the user clicks a button, the JavaScript in this example stores the button name in a hidden HTML control named "Button" and then uses the submit function to post the results to a PHP script, phpbuttons.php.

Example 5-19. Using buttons, phpbuttons.html
 <HTML>     <HEAD>         <TITLE>Using Buttons</TITLE>     </HEAD>      <BODY>         <H1>Using Buttons</H1>         <FORM NAME="form1" ACTION="phpbuttons.php" METHOD="POST">             <INPUT TYPE="HIDDEN" NAME="Button">             <INPUT TYPE="BUTTON" VALUE="Button 1" ONCLICK="button1()">             <INPUT TYPE="BUTTON" VALUE="Button 2" ONCLICK="button2()">             <INPUT TYPE="BUTTON" VALUE="Button 3" ONCLICK="button3()">         </FORM>         <SCRIPT LANGUAGE="JavaScript">             <!--                function button1()                {                    document.form1.Button.value = "button 1"                    form1.submit()                }                function button2()                {                    document.form1.Button.value = "button 2"                    form1.submit()                }                function button3()                {                    document.form1.Button.value = "button 3"                    form1.submit()                }             // -->         </SCRIPT>     </BODY> </HTML> 

You can see what this page looks like in a browser in Figure 5-19.

Figure 5-19. A set of clickable buttons.


Just click a button, and then you can read the name of the clicked button in the hidden field "Button" in your PHP script, as shown in phpbuttons.php, Example 5-20.

Example 5-20. Reading buttons, phpbuttons.php
 <HTML>     <HEAD>         <TITLE>Using Buttons</TITLE>     </HEAD>     <BODY>         <CENTER>         <H1>Using Buttons</H1>         You clicked         <?php             if (isset($_REQUEST["Button"]))                 echo $_REQUEST["Button"], "<BR>";         ?>     </CENTER>     </BODY> </HTML> 

You can see the results in Figure 5-20, where we've determined which button was clicked.

Figure 5-20. Determining which button was clicked.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net