0

I'm using CodeIgniter and I'm having trouble retrieving an array from the input. I have been searching but I can't solve this. The thing is i'm using a button to dynamically add text boxes.

(HTML from view.php)

<?php echo form_open('verifynovareceita'); ?>
(...)
<div id="ings">
       <p>Ingredients:</p>
       <input type="text" name="ings[]"/>
</div>

<input type="button" value="Add another ingrdient" name="add" onClick="addTextBox()">

(...)

<script type='text/javascript'>
    function addTextBox() {
        var ings = document.getElementById("ings");
        var input1 = document.createElement("input");
        input1.type = "text";       
        input1.name = "ings[]";
        ings.appendChild(input1);
    }

And the (visual) result is what it's expected. It creates as many inputs as I wanted. The problem is when it comes to retrieving the data from the POST array:

(PHP from controller)

  $ings = $this->input->post('ings');
  $row_count = count($ings);

$row_count has value 1, no matter how many text boxes existed. Is there a problem with my code? Or is it the fact that i'm using form_open that makes it impossible to work? I've tried to do the same thing, without codeigniter and it worked fine... I appreciate any help! Thank you in advance.

2
  • first print_r($_POST['ings']); and check if it contains array or not because i run this example it works fine for me. May be your problem with this line $this->input->post('ings'); try to use $ings = $_POST['ings']; and check Commented Jan 27, 2014 at 6:37
  • Thank you for the answers. Unfortunatelly, i've tried what you sugested and it didn't work. Adding foreach($ings as $ing) { echo $ing; } Only shows the first input of ings. And trying print_r($_POST['ings']); Only gives the first ing as well (output: Array ( [0] => ing1 )) I have no idea why this is happening... Commented Jan 27, 2014 at 16:18

3 Answers 3

1

$this->input->post() function will not work up to mark if input is such type of array. if input is a such type of array you should use classic mehtod

$ings = $_POST('ings'); $row_count = count($ings);

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

Comments

0

For array inputs, you can use $this->input->post() as below. You have done correctly. You can use foreach as below to get all values from the array.

$ings = $this->input->post("ings");

foreach($ings as $ing)
{
  // your code here
}

Comments

0

You Used ings[] as name. Now if you Retrieve that with $this->input->post("ings"); it will always be a array. Now use Foreach loop or For loop to get the array elements.

Comments

Your Answer

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