Sending form with a large amount of values in PHP
I am developing in a form in which people can order a catering service done by a tray system(ordering foods by try size, medium and large) and I'm having trouble on figuring out on how to do this. My first idea was to code it like this:
<form id="tray" name="tray" method="post" action="send_mail_tray.php" onsubmit='return packageValidator()'>
<table>
<tr>
<td>Pork Fried Rice</td>
<td>
Med.:<br />
Lg. :
</td>
<td>
<input type="text" name="PorkFriedRiceMed" /><br />
<input type="text" name="PorkFriedRiceLg" />
</td>
<td>Vegetable Spring Rolls</td>
<td>
Med.:<br />
Lg. :
</td>
<td>
<input type="text" name="VegetableSpringRollsMed" /><br />
<input type="text" name="VegetableSpringRollsLg" />
</td>
<td>Beef w/ Broccoli</td>
<td>
Med.:<br />
Lg. :
</td>
<td>
<input type="text" name="Beefw/BroccoliMed" /><br />
<input type="text" name="Beefw/BroccoliLg" />
</td>
</tr>
<tr>
<td>
<input type="Submit" value="Submit" />
</td>
</tr>
</table>
</form>
With this method, I would have to be able to post the variable name along with the value. At first I thought this would have been the best method, however, after thinking about it, the list of foods being offered is over 150 which means I would have to create over 300 $_POSTs to get the entire menu and the e-mail I would be sending would have to contain all the items on the list, even if they were not ordered. Is there an easier way to go about making the form I'm doing or is my first method the best way?
Answer
Solution:
Are these values coming out of a database? If not, then they should... or at least you generate the form dynamically from some kind of data structure, e.g.
Then you build the form with
Note that I'm just outputting the item names - not the individual item sizes. This is just to keep this example short.
Once the form's submitted, you can do another loop:
In short, if you build your form properly, it doesn't matter how many fields there are, you can still process them automatically with very little code overhead.
Answer
Solution:
Having so much names can be painful to treat.
Using PHP 5 you can affect names like this
When getting them with $_POST, you can access them by doing
Hint: To save some HTML size, you'd better add a CSS class to your inputs to set the style :
#tray input { width:20px; height:15px }
Answer
Solution:
Pay attention that sending all this data in a post, may also incur in a too long query string error
Another best solution can be also doing it by ajax, because if the list is so long, you can feed back to the user a progress bar inside the saving loop.
The list could be easily split some bunches, encoding in Json and getting in landing page the json data. You can do by example, in a
$.each
jQuery with a max item variable inside.Ajax call can be done easily with jQuery
$.getJson
or normal$.ajax
If you think that this solution can help, we can add more info regarding, but web is fully documented