Mr chinpansee
Mr chinpansee

Reputation: 375

Send values from an javascript array into form value html, to send the values in an html value to php

Difficult title, let me explain

I have values in an javascript array, and I want to put these values into a form wich gets readed in PHP.

I was thinking something like this:

Result.title = the array with the titles filled in by the user. Result.price = the array with the prices filled in from the database

*the html*
<textarea id="products" type="hidden" name="products"/> 
<textarea id="price_products" type="hidden" name="price_products"/> 



*the javascripts*
$("#products").val(result.title);
$("#price_products").val(result.price);


*the PHP*
$products = Trim(stripslashes($_POST['products']));
$price_products = Trim(stripslashes($_POST['price_products']));

$Body .= $products;
$Body .= "\n";
$Body .= $price_products;
$Body .= "\n";

The problem with this is that I'm only sending the first value to the textarea.

Upvotes: 0

Views: 875

Answers (1)

jornane
jornane

Reputation: 1515

Well, since you're using PHP on the server-side, you can use hidden fields with a [] suffix in the field name.

<form method="post" action="post.php">
<script>
var items = ["Hello","World"];
for (var i = 0; i < items.length; i++) {
    document.write('<input type="hidden" name="items[]" value="'+escape(items[i])+'" />')
}
</script>
<input type="submit">
</form>

Then, in post.php, just read $_POST['items'], which will be an array.

Upvotes: 3

Related Questions