Ajax Bible
It is easy to organize the data sent to you from an HTML form into a single array. For example, say you wanted to ask the user’s name and age. You could store those items in an array named $data, as $data['name'] and $data['age']. You could create those array entries like this in formarray.html:
<html> <head> <title> Using form arrays </title> </head> <body> <center> <h1> Using form arrays </h1> <form method="post" action="formarray.php"> Enter your name: <input name="data[name]" type="text"> <br> <br> Enter your age: <input name="data[age]" type="text"> <br> <br> <input type="submit" value="Submit"> </form> </center> </body> </html>
In formdata.php, you can get the $data array like this:
<html> <head> <title> Reading form data in arrays </title> </head> <body> <center> <h1> Reading form data in arrays </h1> Your name is <? $data = $_REQUEST['data']; . . . ?> </center> </body> </html>
Now you can access the user’s name as $data['name']. Here’s how to do that and get the user’s age as well, echoing them to the browser:
<html> <head> <title> Reading form data in arrays </title> </head> <body> <center> <h1> Reading form data in arrays </h1> Your name is <? $data = $_REQUEST['data']; echo $data['name'], "<br>"; ?> Your age is <? $data = $_REQUEST['data']; echo $data['age'], "<br>"; ?> </center> </body> </html>
You can see formarray.html, with the two text fields, in Figure 14.5.
In Figure 14.6, you can see the text recovered from those text fields in formarray.php, where the application has been able to read the text from the $data array.
You’ve gotten some good expertise with PHP now, but each application so far has relied on two pages: an HTML starting page, and a PHP page that handles user input. Can’t you do everything in a single PHP page?