0

I'm trying to get values from an HTML table using PHP and AJAX.

I have this HTML code where users can add more rows to the markup and the SN increases accordingly, thereby increasing the index value of the name attributes for the input tags. For example:

<td class="int"><input type="text" name="balance[1]" class="field"></td>

becomes:

<td class="int"><input type="text" name="balance[2]" class="field"></td>

after the increment.

The code for adding more rows is as follows:

JS:

 function appendRows(e){
    var amountRow = $("#moreRows").val();
    $.ajax({
            type: "POST",
            url: "k.php",
            data: "days="+days+"&amount="+amountRow,
            success: function(response){
                console.log(amountRow);
                //print the rows returned
                $("#rows").append(response);
                $("#moreRows").val('');
                return;
            }
        });
  }
var more = document.querySelector("#moreRows");
  more.addEventListener( 'keydown', function(e){ if(e.keyCode == 13 ) {appendRows()} });

PHP (k.php):

$row_num = $_POST['amount'];
                $days = $_POST['days']; //build days
                $daysHtm = "";
                $rows = "";
                $sn = $_SESSION['x_count'];
                for($i = 1; $i <= $row_num; $i++){
                    $sn++; //increment x
                    $_SESSION['x_count'] = $sn;
                    for($day = 1; $day <= $days; $day++){
                        $daysHtm .= "<td class='int day'>
                                     <input type='text' name='day[".$day."][".$sn."]' class='day field'>
                                     </td>";
                    }
                    $rows .= '<tr class="trow"><td>'.$sn.'</td><td>
                        <input type="text" name="item['.$sn.'] class="field"></td><td>
                        <input type="text" name="type['.$sn.']" class="field"></td>
                        <td class="int"><input type="text" name="qtybf['.$sn.']" class="field"></td>
                        <td class="int">
                        <input type="text" name="qtyrec['.$sn.']" class="field"></td><td class="int">
                        <input type="text" name="balance['.$sn.']" class="field"></td>';
                    $rows .= $daysHtm;  $daysHtm = "";
                    $rows .= '<td class="int"><input type="text" name="qtyreturned['.$sn.']" class="field">
                    </td>
                     <td class="int">
                    <input type="text" name="total['.$sn.'] class="field" id="total-'.$sn.'" disabled>
                    </td>
                    <td class="int">
                    <input type="text" name="qtycf['.$sn.']" class="field" id="qtycf-'.$sn.'" disabled>
                    </td></tr>';    
                }
                echo $rows;

Now the problem is that in my PHP code, the $_POST variable only contains the first row. i.e.:

<td class="int"><input type="text" name="balance[1]" class="field"></td>

and others with index value of [1].

How can I correct this to get the value of other rows? Thanks.

HTML is as follows:

<table class="table table-striped table-sm">
    <thead>
      <tr id="thead">
        <th>S/N</th>
        <th>Item</th>
        <th>Type/Brand</th>
        <th>Quantity B/F</th>
        <th>Quantity Recieved</th>
        <th>Balance</th>
        <th>Quantity Returned</th>
         <th>Total Issued</th>
        <th>Quantity C/F</th>
      </tr>
    </thead>
    <form action="save.php" method="POST" id="spreadsheet">
    <tbody id="rows">
        <tr class="trow">
          <td>1</td>
          <td><input type="text" name="item[1]" class="field"></td>
          <td><input type="text" name="type[1]" class="field"></td>
          <td class="int"><input type="text" name="qtybf[1]" class="field"></td>
          <td class="int"><input type="text" name="qtyrec[1]" class="field"></td>
          <td class="int"><input type="text" name="balance[1]" class="field"></td>
          <td class="int"><input type="text" name="qtyreturned[1]" class="field"></td>
          <td class="int"><input type="text" name="total[1]" class="field" id="total-1" disabled></td>
          <td class="int"><input type="text" name="qtycf[1]" class="field" id="qtycf-1" disabled></td>
        </tr>
    </tbody>
    </form>
</table>
 <div class="col-lg-12">
                            <label>Add more rows:</label>  
                            <input type="number" name="moreRows" id="moreRows" placeholder="10">
                      </div>

I have jQuery as follows:

$("#spreadsheet").on('submit', (function(e){
    e.preventDefault();
    $.ajax({
        type: 'POST',
        url: $(this).attr('action'),
        data: new FormData(this),
        contentType: false,
        cache: false,
        processData: false,
        success: function(response){
            $("#result").append(response);
        },
        error: function(){
            console.log("ERROR occured while trying to upload with ajax");
        }
    });
    return;
}));

And PHP (save.php):

print_r($_POST); //only returns the first row
goodhand
  • 189
  • 1
  • 1
  • 9
  • 1
    I don't see any other rows in your table. – u_mulder Sep 18 '17 at 13:53
  • Can we see the JS that adds rows? – Matt S Sep 18 '17 at 13:54
  • I have a field where users can type how many more rows they need to append and then the row(s) are appended – goodhand Sep 18 '17 at 13:54
  • You don't want the `1` in the array's of the names, so use `name="qtycf[]"`, without the `1`, in all the different names, but keep the names different, of course. I also see identifiers with a `1` in them... they will be repeated, which should not happen. – KIKO Software Sep 18 '17 at 13:57
  • define `
    ` tag outside of ``.
    – chirag satapara Sep 18 '17 at 13:59
  • 1
    [edit] your question please. – u_mulder Sep 18 '17 at 14:00
  • @KIKOSoftware how does that work? I am going to have other rows as well. Also I need to attach it to the SN i.e the `qtycf[1]` is attached to `item[1]` or any other fields in the same SN – goodhand Sep 18 '17 at 14:00
  • @u_mulder why? Can you point to anywhere that you want me to make clearer? – goodhand Sep 18 '17 at 14:01
  • 1
    @I_aM_SaMuel: Don't add elements of your question as a comment, put them in the question. – KIKO Software Sep 18 '17 at 14:03
  • @KIKOSoftware I have edited the question...any help now? – goodhand Sep 18 '17 at 14:19
  • What exactly do you mean by "the $_POST variable only contains the first row"? You are not posting rows at all, you are posting two individual (presumably integer) values. Also, you're still omitting some HTML. I don't see any `moreRows` element in the HTML that you posted, and I also don't see any sort of submit button for your form. – Patrick Q Sep 18 '17 at 14:24
  • @PatrickQ I am not using any save button, i am automatically saving the values after 5 seconds (I didn't think that was necessary to include in the code). After 5 seconds, save.php prints the values stored in `$_POST` and that only returns the first row (html), even when there are more rows as allowed by moreRows (to append more rows to the markup). – goodhand Sep 18 '17 at 14:30
  • @goodhand: Yes, much better. You are making this quite complex. I stick to my initial recommendation: Leave out the indexes, or what you call `$sn`, out of the names of the inputs altogether. See [the answers here](https://stackoverflow.com/questions/4688880/html-element-array-name-something-or-name-something?answertab=active#tab-top). – KIKO Software Sep 18 '17 at 14:33
  • To be honest, I don't know why you're using PHP to create the HTML for the additional rows. I feel like this would be much easier with javascript/jquery. – Patrick Q Sep 18 '17 at 14:41
  • @Patrick Q: Not only on keydown, there's also a check for the key, and only then rows will be appended. – KIKO Software Sep 18 '17 at 14:43
  • @KIKOSoftware True, I didn't spot the keycode check. – Patrick Q Sep 18 '17 at 14:45
  • Also, regarding `"days="+days`, I don't see `days` defined. – Patrick Q Sep 18 '17 at 14:47
  • @PatrickQ `days` is defined. Its just in another scope. Maybe this will help you understand my question: The system am building generates a table like above depending on the date you select from a calendar (JQUERY datepicker), after that i get the number of days in the month selected (which is why am using php to generate the html and not JS) and then the days are appended to the table above. `days` is defined as part of the return values from the `PHP` code that generates the html with the days. – goodhand Sep 18 '17 at 14:59
  • Now when the markup for the days are returned, bearing in mind that users can append more rows I have made the name attribute for days as `day[1][23]` which interprets to `day 23` for `row 1`. So @KIKOSoftware, how does this work if I remove the indexes – goodhand Sep 18 '17 at 15:02
  • I think there's a little too much going on here for us to be able to give you a good answer. You should try to narrow things down a bit, making use of your browser's Network tab to view what requests are being sent to your server. Are the requests as you expect them to be? "i get the number of days in the month selected (which is why am using php to generate the html and not JS)". I don't see a reason why you can't get the number of days in a month in JS. At this point, I think you're really going to have to do some debugging on your own to really pinpoint where things are going wrong. – Patrick Q Sep 18 '17 at 15:12
  • @goodhand: I thought the link I gave you made clear how it works? Names don't need indexes for them to be posted in order. Apart from that there are many other things you could improve. What you could do is try to get a **working spreadsheet** and then post it, completely, on [Code Review](https://codereview.stackexchange.com), there you might get good suggestions for improvement. SO is more for programming problems, preferably one at a time. – KIKO Software Sep 18 '17 at 22:19

0 Answers0