Reputation: 1775
I'm sure I'm going about this the wrong way, so I'm here to ask.
I have a form that's sending out multiple HTML form $_POST
keys (name
attribute) and values (value
attribute).
The looks HTML like this:
<input type="text" value="0" name="Quantity">
I have some jQuery multiplying price by quantity and submitting them to the form.
Here is a link to a pen demonstrating the form.
That part works fine. Then on form submit, I'm just serializing all the data and sending it through with serialize()
. Simplified example...
$('form').on('submit', function (event) {
event.preventDefault();
var formValues = $(this).serialize();
$.ajax({
type: 'POST',
url: 'send.php',
data: formValues
});
});
And the PHP looks like this (simplified!)
foreach ($_POST as $key => $value) {
$message .= $key.': '.$value. "\n";
}
So, everything works properly - the JavaScript adds up all the quantities and sends it to the PHP. My only issue is you can't have multiple name
attributes sending out, so I have to change them for each input.
<input type="text" value="0" name="Quantity1">
<input type="text" value="0" name="Quantity2">
So, I guess my question is how to change the name attribute to something more readable in an e-mail.
In other words, the e-mail sends out as:
Quantity1: 10
Product 2
and I want it to just be...
Quantity: 10
Product 2
Upvotes: 0
Views: 881
Reputation: 2050
For all your inputs you can do <input type="text" value="0" name="quantity[]">
and in your php
foreach($_POST['quantity'] as $quantity){
.... your stuff here
}
Seems like your products and quantities are in order and the same length i.e for every product there is only one quantity field. If that's true you can iterate through both in one loop.
$quantities = $_POST['quantity']; // array of quantities
$products = $_POST['products']; // array of products
for ($i = 0; $i < count($_POST['quantity']); $i++){
$quantity = $quantities[$i];
$product = $products[$i];
.... do more stuff here
}
Upvotes: 2
Reputation: 2229
Ah this is simple, you can use a namemd array for this.
Something like this :-
<input type="text" value="0" name="quantity[]">
Now in your php, you can access the values in this way.
if(is_array($_POST['quantity']))
{
foreach($_POST['quantity'] as $quantity)
{
//access the quantity.
//so the first time the loop runs, the quantity is for product 1
//second time -> Product 2
//and so on
}
}
Upvotes: 1