简体   繁体   中英

How do i get the javascript dynamic row values in php?

jsfiddle

I'm trying to print the input text field values on nextpage (postdata.php). But it always print the first row result only. I didn't get the remaining row values on next page. I've posted my full codes on jsfiddle.. How do i get the remaining js dynamic row values in php (postdata.php page)?

JS

$(document).ready(function(){
    $("span").click(function(){
        $("#container").append('<tr><td>Email : </td><td><input type="text" name="email[]" placeholder="Email id" /></td> &nbsp; <td>Name : </td><td><input type="text" name="name[]"  placeholder="Your Name "/></td>&nbsp; <td><a title="Delete this row" href="javascript:void(0);" class="remove">Del</a></td></tr>');
    });
    $("#container").on('click','.remove',function(){
        $(this).parent().parent().remove();
    });
});

Php

<?php
    echo "
    <table>
    <tr>   
        <td>
            Email :
        </td>
        <td>
             $_POST[email]
        </td>
        <td>
            Name :
        </td>
        <td>
             $_POST[name]
        </td>
    </tr>
    </table>";
?>

When you add square brackets to the name of an input field, PHP will receive it's value as an array. Your JS code is fine, but the PHP code doesn't handle arrays at all. Look at the following:

echo "
<table>";
if(!is_array($_POST['email'])) {
    $_POST['email'] = array($_POST['email']);
    $_POST['name'] = array($_POST['name']);
}

foreach($_POST['email'] as $key => $email) {
    // get the corresponding name to the email
    $name = $_POST['name'][$key];
    echo "<tr>   
        <td>
            Email :
        </td>
        <td>
             $email
        </td>
        <td>
            Name :
        </td>
        <td>
             $name
        </td>
    </tr>";
}

echo "</table>";

Note: This code will check whether multiple values were submitted or not and will work in both scenarios.

Since name of fields you declared is array the $_POST becomes multidimensional array.So try like this

<?php
   $size = sizeof($_POST['email']);
   echo "<table>" ;
   for($i=0; $i<$size;$i++)
   {
    echo "
      <tr>   
        <td>
            Email :
        </td>
        <td>
             ".$_POST['email'][$i]."
        </td>
        <td>
            Name :
        </td>
        <td>
             ".$_POST['name'][$i]."
        </td>
    </tr>
    ";
    }
     echo "</table>";
?>

also in your html change names of Name and Emai l field to name[] and email[] respectively.Also you have misplaced the form tag. It starts after <table> and ends after <table> . which was not correct. so place form tag before table tag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM