Reputation: 197
In PHP, I have an array. I would like to send all values in the array to the next page (result.php). When I receive the values in $_POST, can I get them in the array as they were? (or I can only get the values of the array separately or concatenated, and re-generate the array afterwards?)
I tried the following code, but it only concatenates the values in the array, so it is not satisfactory.
Please let me know what would be the best practice either way. Of course, I prefer to keep the original array intact!
Thank you!
<form class="form_container validationForm" action="result.php" method="post">
<input type="hidden" name="targetobject[]" value="
<?php $postvalue = array("Volvo", "BMW", "Toyota"););
foreach($postvalue as $value){echo $value;}
?>
">
<input type="text" class="form-control validationInput" name="search" placeholder="Type a search keyword"><br><button class="btn btn-primary" type="submit">Search</button></div></form>
//The following is result.php
<?php $targetobject = $_POST['targetobject'];
echo var_dump($targetobject);
?>
array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }
Upvotes: 0
Views: 55
Reputation: 8975
Well, if you examine the HTTP result of the above suggestions, you'll see that they work by repeating the POST variable-names in an organized way. And this approach is certainly not wrong.
Another way to do it is to send the data JSON-encoded as the value of a single field. This approach allows truly-arbitrary data structures to be encoded and represented. Essentially, though not quite, "classic AJAX."
So, "the choice is yours."
Upvotes: 2
Reputation: 488
Or with less letters:
<?php $postvalue = array("Volvo", "BMW", "Toyota"); ?>
<form class="form_container validationForm" action="result.php" method="post">
<input type="hidden" name="targetobject" value='<?=json_encode( $postvalue ); ?>'>
<input type="text" class="form-control validationInput" name="search" placeholder="Type a search keyword"><br>
<button class="btn btn-primary" type="submit">Search</button>
</form>
//The following is result.php
<?php
$targetobject = json_decode( $_POST['targetobject'], $assoc = true );
echo var_dump($targetobject);
?>
Upvotes: 1
Reputation: 1823
You need to put each value in a separate hidden input
with a name containing []
. Try this :
<form class="form_container validationForm" action="result.php" method="post">
<?php $postvalue = ["Volvo", "BMW", "Toyota"]; ?>
<?php foreach ($postvalue as $val) : ?>
<input type="hidden" name="targetobject[]" value="<?php echo $value; ?>">
<?php endforeach; ?>
</form>
<input type="text" class="form-control validationInput" name="search" placeholder="Type a search keyword"><br><button class="btn btn-primary" type="submit">Search</button></div></form>
//The following is result.php
<?php $targetobject = $_POST['targetobject'];
echo var_dump($targetobject);
?>
Upvotes: 1