0

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.

3
  • either your "result" is a single item, or you need a loop to grab multiple items. Are the products/prices an array? would it be possible to execute foreach (result.title) { perform action } Commented Jun 9, 2014 at 13:43
  • Can you please show them in their own places and not all the 3 languages' code extracts? Commented Jun 9, 2014 at 13:44
  • You have to loop through all the results and append the values Commented Jun 9, 2014 at 13:44

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Its not an array in the post.php, it only gives the last value!
You're sure you put [] at the end of the name? Hasn't failed me since PHP 4-ish.
you're right, it is returning an array right now, (php noob here), any tips converting this array into readable object to deliver in a mail? Edit: "Results: " . print_r( $items, true );worked for me, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.