简体   繁体   中英

PHP - HTML best practices to handle (submit) generated rows

I have html table generated via ajax. And last column on this table contains button. My question is what is the best practice to submit these rows (only one at time. I need use this method to amend records). Is it worth to wrap each row with

<form> 
     <input type="hidden" value="hidden value"> 
     <input type="submit">
</form>

Or people using something difference? Reason why i'm asking for is because i'm worry about very long list example 1k rows or 10k rows (that means i will have 1k or 10k forms on a page).

You can just use a hyperlink (which you can style to look like a button using CSS if you want). eg:

<a href="edit.php?id=1">Edit</a>

where the value you give as the "id" parameter is the primary key of the record in that row.

Then in edit.php look for the id value using $_GET["id"] and fetch the appropriate record from the DB.

As Progrock advises , a form element may only be used " where flow content is expected " (ie not as a direct child of table or tr ).

HTML 5 introduces a form attribute as a workaround:

<form id="row_1">
    <input type="hidden" name="id" value="pk1">
</form>
<form id="row_2">
    <input type="hidden" name="id" value="pk2">
</form>
<table>
    <tr>
        <td> <input type="text" name="attribute1" form="row_1"> </td>
        <td> <input type="submit" form="row_1"> </td>
    </tr>
    <!-- and so on for each row -->
</table>

It has been brought to my attention that in this case, there is no direct user input being submitted, but only generated contents.

Well, then the solution is even simpler:

<table>
    <tr> <td>
        <form id="row_1">
            <input type="hidden" name="id" value="pk1">
            <input type="hidden" name="attribute1" value="whatever">
            <input type="submit">
        </form>
    </td> </tr>
    <!-- and so on for each row -->
</table>

I thought I'd have a go without form elements, working with editable table cells. Within each row you provide a button. And when you click it, an ajax post is made of the cell values.

You could have a non js fall back where the save button is replaced for an edit button that takes you to another page with a single form.

Forgive my JS.

I have the session storage in there just to check the concept.

<?php
session_start();
var_dump($_SESSION);

$data = array(
    23 => ['triangle', 'green', '2'],
    47 => ['square', 'red', '3'],
    17 => ['pentagon', 'pink', '4']
);

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Save state here
    $_SESSION['submission'] = $_POST;
}
?>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
        <script>
            $(function() {
                $('button').click(function() {
                    // Get all table cells in the buttons row
                    var $cells = $(this).closest('tr').find('td[contenteditable="true"]');
                    var jsonData = {};
                    $.each($cells, function() {
                        jsonData[get_table_cell_column_class($(this))] = $(this).text().trim();
                    });
                    jsonData['id'] = $(this).attr('id');
                    $.post('',jsonData, function() {
                        alert('Saved.');
                    });
                });

                function get_table_cell_column_class($td)
                {
                    var $th = $td.closest('table').find('th').eq($td.index());

                    return $th.attr('class');
                }
            });
        </script>
    </head>
    <body>
        <table>
            <thead>
                <tr>
                    <th class="shape">Shape</th>
                    <th class="colour">Colour</th>
                    <th class="width">Width</th>
                    <th>Ops</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($data as $key => $row) { ?>
                    <tr>
                        <?php foreach($row as $field) { ?>
                            <td contenteditable=true>
                                <?php echo $field ?>
                            </td>
                        <?php } ?>
                        <td>
                            <button id="<?php echo $key ?>">Save</button>
                        </td>
                    </tr>
                <?php } ?>
            </tbody>
        </table>
    </body>
</html>

You can use the following

<table id="YourTableId">
    ...
   <tr data-id="yourrowId">
        <td class="col1"> value1</td>
        <td class="col2"> value2</td>
        <td class="col3"> value3</td>
        <td class="actions">
             <a href="#"> Submit</a>
        </td>
   </tr>
   ....
</table>

your javascript code will be like

$(document).ready(function (){
     $('#YourTableId a').off('click').on('click',function(e){
          e.preventDefault();
          var tr = $(this).closest('tr')
          var data={ // here you can add as much as you want from variables
            'id' : tr.data('id), // if you want to send id value
            'col1': tr.find('.col1').text(),
            'col2': tr.find('.col2').text(),
            'col3': tr.find('.col3').text(),
          };

          $.ajax({
              method: 'post',
              url: 'your url goes here',
              data: data,
              success: function(result){
                  // handle the result here
              }
          });
     });
});

Hope this will help you

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