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);
}
1

2 Answers 2

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'];
Sign up to request clarification or add additional context in comments.

Comments

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"?

Comments

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.