The Web Design Group

... Making the Web accessible to all.

Welcome Guest ( Log In | Register )

 
Reply to this topicStart new topic
> processing javascript array with PHP
joyful
post Aug 28 2011, 01:39 PM
Post #1


Advanced Member
****

Group: Members
Posts: 239
Joined: 15-November 10
Member No.: 13,147



Hey!

I am dynamically creating form inputs with this script:
CODE

var counter = 1;
var limit = 40;
function addInput(divName){
     if (counter == limit)  {
          alert("You have reached the limit of steps: " + counter);
     }
     else {
          var newdiv = document.createElement('div');
          newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
          document.getElementById(divName).appendChild(newdiv);
          counter++;
     }
}

(I found the above script here)

This script works great! The issue arises when I attempt to process the data with PHP:
CODE

$myInputs = $_POST["myInputs"];
foreach ($myInputs as $eachInput) {
     echo $eachInput . "<br>";
}

I seem to only be able to get the contents of the first input using the above script. What am I doing wrong? Should this work? I followed the tutorial at www.randomsnippets.com exactly; yet, it seems not to work!

Thanks in advance! blush.gif

--


--------------------
"When I was 5 years old, my mother always told me that happiness was the key to life. When I went to school, they asked me what I wanted to be when I grew up. I wrote down ‘happy’. They told me I didn’t understand the assignment, and I told them they didn’t understand life.” ~ John Lennon
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post Aug 28 2011, 07:31 PM
Post #2


.
********

Group: WDG Moderators
Posts: 6,049
Joined: 10-August 06
Member No.: 7



QUOTE(joyful @ Aug 28 2011, 08:39 PM) *

(I found the above script here)


There's no ACTION attribute or submit button in the form, so it can't submit:

CODE
<script src="/wp-includes/js/addInput.js" language="Javascript" type="text/javascript"></script>
<form method="POST">
     <div id="dynamicInput">
          Entry 1<br><input type="text" name="myInputs[]">
     </div>
     <input type="button" value="Add another text input" onClick="addInput('dynamicInput');">
</form>

(if there's an ACTION attribute you might use the Enter key instead of a submit button when there's only a single textfield, though).

QUOTE
The issue arises when I attempt to process the data with PHP:
CODE

$myInputs = $_POST["myInputs"];
foreach ($myInputs as $eachInput) {
     echo $eachInput . "<br>";
}

Seems OK. But as a side-note you must sanitize the POST data, otherwise malicious users can inject any kind of content into your web page.

QUOTE
I seem to only be able to get the contents of the first input using the above script. What am I doing wrong?

No idea. Have you given the generated textfields the same NAME as the first (static) one? Does the javascript place them inside the form (and not outside)?

QUOTE
Should this work?

With a correct form, yes.


--------------------
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
joyful
post Aug 29 2011, 01:31 PM
Post #3


Advanced Member
****

Group: Members
Posts: 239
Joined: 15-November 10
Member No.: 13,147



Thanks for the reply Christian.

First of all, I did not post the actual HTML form. I hoped the content of it could be assumed, however, in hindsight, I believe I should have posted it:
CODE

<form method='POST' action='myfile.php'>";

    <div id='dynamicInput'>
        Step 1<br><input type='text' name='myInputs[]' />
    </div>
    <input type='button' value='Add another step' onClick='addInput(".'"dynamicInput"'.");'>    
                
    <div id='submitButtonWrap'><input type='submit' value='Create' name='addSubmit' /></div>";
                
</form>";


As posted above, this is my java script:
CODE

var counter = 1;
var limit = 40;
function addInput(divName){
     if (counter == limit)  {
          alert("You have reached the limit of steps " + counter + " inputs");
     }
     else {
          var newdiv = document.createElement('div');
          newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
          document.getElementById(divName).appendChild(newdiv);
          counter++;
     }
}


And PHP:

CODE

$myInputs = $_POST["myInputs"];
foreach ($myInputs as $eachInput) {
     echo $eachInput . "<br>";
}


Also, what do you mean by "sanitize the data"? How can I do that?
As stated above, the issue with the above javascript/HTML/PHP is that it only submits the first input. What am I doing wrong?

Thanks a lot for your help! smile.gif

--


--------------------
"When I was 5 years old, my mother always told me that happiness was the key to life. When I went to school, they asked me what I wanted to be when I grew up. I wrote down ‘happy’. They told me I didn’t understand the assignment, and I told them they didn’t understand life.” ~ John Lennon
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post Aug 29 2011, 03:12 PM
Post #4


.
********

Group: WDG Moderators
Posts: 6,049
Joined: 10-August 06
Member No.: 7



QUOTE(joyful @ Aug 29 2011, 08:31 PM) *

Thanks for the reply Christian.

First of all, I did not post the actual HTML form. I hoped the content of it could be assumed, however, in hindsight, I believe I should have posted it:
CODE

<form method='POST' action='myfile.php'>";

    <div id='dynamicInput'>
        Step 1<br><input type='text' name='myInputs[]' />
    </div>
    <input type='button' value='Add another step' onClick='addInput(".'"dynamicInput"'.");'>    
                
    <div id='submitButtonWrap'><input type='submit' value='Create' name='addSubmit' /></div>";
                
</form>";


The ending "; and the nested quotes makes it look like HTML generated by PHP (but incorrectly so). Maybe the nested quotes are messed up. unsure.gif

QUOTE
Also, what do you mean by "sanitize the data"? How can I do that?

When printing content on a PHP web page, use e.g. htmlspecialchars(). In an SQL query, use e.g. mysql_real_escape_string() to avoid SQL injections.


--------------------
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
joyful
post Aug 29 2011, 05:11 PM
Post #5


Advanced Member
****

Group: Members
Posts: 239
Joined: 15-November 10
Member No.: 13,147



Hey! Sorry, it was generated with PHP... I forgot to remove all the remnants of that. By the way, the fact that it was generated with PHP is of no relevance to the issue... Right?.

Here is what it looks like (full, in the PHP):
CODE

            echo "<form method='POST' action='requests.php'>";
                
            echo "<div id='dynamicInput'>
                        <div>Step 1<br><input type='text' name='myInputs[]' /></div>
                  </div>
                        <input type='button' value='Add another step' onClick='addInput(".'"dynamicInput"'.");'>
                        ";    
                
            echo "<div id='submitButtonWrap'><input type='submit' value='Create' name='addSubmit' /></div>";
                
            echo "</form>";


I really don't understand what I am doing wrong. I feel like I have done everything it the tutorial. When I echo the array (an array that had 3 inputs contents) in PHP I get this:
CODE

Array ( [0] => First Inputs Contents )

The array only was one row when it should have all 3. Do you see what I am doing wrong?

Again, Thanks a lot for all the help smile.gif

--


--------------------
"When I was 5 years old, my mother always told me that happiness was the key to life. When I went to school, they asked me what I wanted to be when I grew up. I wrote down ‘happy’. They told me I didn’t understand the assignment, and I told them they didn’t understand life.” ~ John Lennon
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Brian Chandler
post Aug 29 2011, 10:36 PM
Post #6


Jocular coder
********

Group: Members
Posts: 2,224
Joined: 31-August 06
Member No.: 43



It helps to show the html that is being generated, not the php program generating it. For example, in the middle of the echo we have

...ut(".'"dynamicInput"'.");'>...

which produces

...ut("dynamicInput");'>...

(but which would be easier to read if written

...ut(\"dynamicInput\");'>...


Anyway, I think the problem is that you have three [variable] text inputs with the same name, "myinputs[]". In the case of checkboxes, you can use this PHP (fake) array name to get more than one value for the same _name_ input, but it's not obvious that you can for text input. First thing to do is to check by printing out the complete $_POST array in the PHP form handler. Also print out the raw POST data (can't remember how to do that)...

But I think it's cleaner to avoid the whole business of duplicate _name_ values. Can't you make the javascript generate additional text inputs with name=input2, name=input3, etc?


--------------------
Brian Chandler
Nothing in this post constitutes "commercial solicitation". PayPal does not solicit residents of Japan. Contents may settle in transit. "Legal mind" may or may not be brain-damaged.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post Aug 30 2011, 06:03 AM
Post #7


.
********

Group: WDG Moderators
Posts: 6,049
Joined: 10-August 06
Member No.: 7



QUOTE(Brian Chandler @ Aug 30 2011, 05:36 AM) *

I think the problem is that you have three [variable] text inputs with the same name, "myinputs[]". In the case of checkboxes, you can use this PHP (fake) array name to get more than one value for the same _name_ input, but it's not obvious that you can for text input.

It's permitted by PHP, see code example here: http://www.php.net/manual/en/faq.html.php#faq.html.arrays (note that the default TYPE of INPUT is "text").

The following works for me. I changed the ACTION to the same page, so now you'll get a notice and warning when the page is first loaded (because the form is not yet submitted):

CODE
<?php
$myInputs = $_POST["myInputs"];
foreach ($myInputs as $eachInput)
{
     echo $eachInput . "<br>";
}

echo "<form method='POST' action=\"\">";
echo "<div id='dynamicInput'>
            <div>Step 1<br><input type='text' name='myInputs[]' /></div>
      </div>
            <input type='button' value='Add another step' onClick='addInput(".'"dynamicInput"'.");'>
            ";

echo "<div id='submitButtonWrap'><input type='submit' value='Create' name='addSubmit' /></div>";
echo "</form>";
?>
<script type="text/javascript">
var counter = 1;
var limit = 40;
function addInput(divName)
{
     if (counter == limit)
     {
          alert("You have reached the limit of steps: " + counter);
     }
     else
     {
          var newdiv = document.createElement('div');
          newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
          document.getElementById(divName).appendChild(newdiv);
          counter++;
     }
}
</script>


QUOTE
But I think it's cleaner to avoid the whole business of duplicate _name_ values. Can't you make the javascript generate additional text inputs with name=input2, name=input3, etc?

But then you must tease them apart in the PHP, which seems much messier.


--------------------
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Brian Chandler
post Aug 30 2011, 02:23 PM
Post #8


Jocular coder
********

Group: Members
Posts: 2,224
Joined: 31-August 06
Member No.: 43



QUOTE(Christian J @ Aug 30 2011, 08:03 PM) *

QUOTE
But I think it's cleaner to avoid the whole business of duplicate _name_ values. Can't you make the javascript generate additional text inputs with name=input2, name=input3, etc?

But then you must tease them apart in the PHP, which seems much messier.


Not really. And there is something profoundly repugnant in programming terms in having [sort-of] variable names including [] characters.

(Handling names like 'input1' 'input2' really is trivial -- something like:

CODE

$i = 1;
while ($text = $_POST['input'. $i++])  // assuming text box must be nonempty
{
...process $text...
}



--------------------
Brian Chandler
Nothing in this post constitutes "commercial solicitation". PayPal does not solicit residents of Japan. Contents may settle in transit. "Legal mind" may or may not be brain-damaged.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post Aug 30 2011, 07:41 PM
Post #9


.
********

Group: WDG Moderators
Posts: 6,049
Joined: 10-August 06
Member No.: 7



QUOTE(Brian Chandler @ Aug 30 2011, 09:23 PM) *

there is something profoundly repugnant in programming terms in having [sort-of] variable names including [] characters.

The NAME attribute is not a variable, and in the actual PHP the square brackets are not used. But in javascript such NAME attribute values seems to complicate things.

QUOTE

(Handling names like 'input1' 'input2' really is trivial -- something like:

That was indeed simple (despite the "Undefined index" notice when it reaches the end, but I guess such a notice is not harmful).



--------------------
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
joyful
post Sep 12 2011, 02:10 PM
Post #10


Advanced Member
****

Group: Members
Posts: 239
Joined: 15-November 10
Member No.: 13,147



Hey!

Thanks a lot Christian and Brian,
I ended up doing this with Christian's method (javascript array).

Thanks!
Cheers!


--------------------
"When I was 5 years old, my mother always told me that happiness was the key to life. When I went to school, they asked me what I wanted to be when I grew up. I wrote down ‘happy’. They told me I didn’t understand the assignment, and I told them they didn’t understand life.” ~ John Lennon
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post

Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 



- Lo-Fi Version Time is now: 20th September 2014 - 08:59 AM