0

I build a questionnaire, actually a kind of a online survey. I came across major issue about the code below. No matter how hard I try, my array obviously doesn't return anything. I provide a full code below, and it will be really helpful if anyone can locate errors. The result returns empty page.

HTML FORM

<form action="process.php" method="post"> 
Title: <br/><input type="text" name="title"><br/><br/> 
Question 1: <br/><textarea name="ask[1]"></textarea><br/>
Question 2: <br/><textarea name="ask[2]"></textarea><br/> 
Question 3: <br/><textarea name="ask[3]"></textarea><br/><br/> 

<input type="submit" name="submit" value="PROCEED"> 
</form> 

PHP FILE PROCESS.PHP

<?php
$blah = "";
$title = $_POST['title'];
$ask = array();

for($j=1; $j<4; $j++) {
    $ask[$j] = $_POST['ask$j'];

if($ask[$j] != "") {
    $area = '<textarea name="ans11"></textarea>';
    $addmore = '<button type="button" name="addmore" onClick="addmore('.$j.');">Add more</button>';
    $blah .= $j.'): '.$ask[$j].'<br/>'.$area.'<br/><div id="inner$j"></div>'.$addmore.'<br/><br/>';
}}  
echo $blah;
?>

JAVASCRIPT FILE

var am = [];
for(var i=1; i<101; i++){
  am[i] = 1;
}
function addmore(index) {
        am[index]++;
        var textarea = document.createElement("textarea");
        textarea.name = "ans" + index + am[index];
        var div = document.createElement("div");
        div.innerHTML = textarea.outerHTML;
        document.getElementById("inner"+index).appendChild(div);
}
user3392725
  • 65
  • 2
  • 9
  • possible duplicate of [HTML Element Array, name="something\[\]" or name="something"?](http://stackoverflow.com/questions/4688880/html-element-array-name-something-or-name-something) – Patrick Evans Mar 19 '14 at 18:01

2 Answers2

1

I believe your problem is how you're capturing the array in PHP. These lines:

for($j=1; $j<4; $j++) {
    $ask[$j] = $_POST['ask$j'];

Should be:

for($j=1; $j<4; $j++) {
    $ask[$j] = $_POST['ask'][$j];

Or more simply:

$ask = $_POST['ask'];
larsAnders
  • 3,813
  • 1
  • 15
  • 19
0

PHP will convert form elements that specifies an array.

ask[...] will be converted to an array:

$_POST = array(
    'ask' => array(...)
)

You can observe the behavior by var_dumping the $_POST array: var_dump($_POST);

See HTML Element Array, name="something[]" or name="something"?

Community
  • 1
  • 1
Martin Samson
  • 3,970
  • 21
  • 25