简体   繁体   中英

Append a row to an html table with Jquery?

I have a simple form that inserts data into a mysql database and displays the data from the database including the one just posted with ajax in a table. Currently the whole table gets refreshed after submitting the form but I am trying to figure how I can append a row to the table results that displays the data just submitted. Can anyone explain how I can achieve this?

The form

<div class="form-group">
    <form class="" action="" id="post_data" method="post">
        <label>
                Post Data
              </label>
        <input id="input" name="input" type="text" class="form-control input-md">
</div>
<button type="submit" class="btn pull-right btn-primary" id="submit">
              Save
            </button>
</form>

<div class="display" id="display"></div>
</div>

<script>
    $(document).ready(function() {
        $('#post_data').submit(function() {
            $.ajax({
                url: 'process.php',
                type: 'POST',
                dataType: 'html',
                data: $(this).serialize(),
                success: function(newContent) {
                    $('#display').html(newContent);
                }
            });

            return false;
        });
    });
</script>

Process.php

$stmt = $db_conx->prepare('INSERT INTO ajax_test (input) VALUES (?)');
$stmt->bind_param('s', $input);
$stmt->execute();
$sql = "SELECT input FROM ajax_test";
$result = mysqli_query($mysqli, $sql);


while ($row = $result->fetch_assoc()) {
    echo "<tr>";
    echo "<td>" . $id . "</td>";
    echo "<td>" . $row["input"] . "</td>";
    echo "</tr>";
}
}
mysqli_close($mysqli);

use append() instead of html();

$('#display').append(newContent);

or if you want to add new content top of table

$('#display').prepend(newContent);

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