首页 文章

在通过表单提交输入新行后,如何使用AJAX刷新数据库表?

提问于
浏览
0

长时间读者,第一个问题 . 我应该注意到我是初学者 .

我的页面显示记录的唱片 . 它有两个部分:1 . 在 records 表中输入新行的表单 . 2. records 表从数据库中回显 .

目前,用户可以填写表单,单击"submit"并将新行插入到 records 表中 .

我想使用AJAX,以便在单击表单的提交按钮时自动刷新 records 表 .

我将在下面发布缩短版本的代码 .

表单已经通过AJAX提交了这段代码(我从教程中获得):

$(function() {
    // Get the form.
    var form = $('#formInsert');
    // Get the messages div.
    var formMessages = $('#form-messages');
    // Set up an event listener for the contact form.
    $(form).submit(function(e) {
        // Stop the browser from submitting the form.
        e.preventDefault();
        // Serialize the form data.
        var formData = $(form).serialize();
        // Submit the form using AJAX.
        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        })
        .done(function(response) {
            // Make sure that the formMessages div has the 'success' class.
            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');
            // Set the message text.
            $(formMessages).text(response);
            // Clear the form.
            $('#front_cover').val('');
            [many lines omitted]
        })

        .fail(function(data) {
            // Make sure that the formMessages div has the 'error' class.
            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');
            // Set the message text.
            if (data.responseText !== '') {
                $(formMessages).text(data.responseText);
            } else {
                $(formMessages).text('There\'s some kinda love, and there\'s some kind error.');
            }
        });
    });
});

这是HTML:

<div id="form-messages"></div>
<form id="formInsert" method="post" action="formInsert.php">
[lots of form fields]
<button type="submit" class="btn btn-outline-success" id="submitDB" name="submit">Submit</button>
</form>        

<!-- Here is the echoed table from database-->
<hr>
<div id="databaseTable">        
   <? include('tableData.php'); ?>
</div>

这是表单操作的PHP(formInsert.php):

<?php
[database connection here]
// This script inserts a record into the records table
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $band = strip_tags(stripslashes(trim(htmlentities($_POST['band']))));
    $title = strip_tags(stripslashes(trim(htmlentities($_POST['title']))));
    //other fields omitted for space

    $result = $db->insert('records', array(
        "band"=> $band, 
        "title"=> $title, 
        //other fields omitted for space
    ));
        if ($result) { // If it ran OK
        $success =  '<div class="alert alert-success" role="alert">entry successful</div>'; 
}

最后这里是dataTable.php . 这就是我想在按下“提交”按钮时通过AJAX自动更新的内容 .

<table class='table-sm' id='recordsDB'>
        <colgroup>
            <col style='width:'><col style='width:'><col style='width:'><col style='width:150px'><col style='width:'>
            <col style='width:'><col style='width:'><col style='width:350px'><col style='width:350px'><col style='width:'>
            <col style='width:'><col style='width:'><col style='width:'><col style='width:'><col style='width:'>
            <col style='width:'><col style='width:'><col style='width:'><col style='width:'><col style='width:350px'>
        </colgroup>
    <tr>
    <th>Edit </th>  
    <th> Band </th> 
    <th> Title </th>   
    // other fields omitted for space

    <?php       
     $db = app('db');
    // Make the query            
    $result = $db->select(
        "SELECT * FROM `records` ORDER BY db_code ASC, band ASC, title ASC"
        );
    // output data of each row
    foreach($result as $row) {
        echo "<tr><td><a href='edit_record.php?release_id=" .$row['release_id'] . "'>Edit</a></td> 
        <td>".$row["band"]."</td>
        <td>".$row["title"]."</td>;
        */other fields omitted for space/*
    }   
    ?>
    </table>

我非常感谢你这么做!当单击提交按钮进行新行INSERT时,是否仍然使用AJAX(或更新当前的AJAX)刷新表?

1 回答

  • 0

    您当前正在呈现表服务器端并通过AJAX更新它将修改表并呈现新行客户端 . 它可以做到,但我强烈建议以同样的方式做到这一点 .

    给定现有代码的最简单方法是将插入字段简单地发布到同一页面 . 然后检查POST数据并根据需要执行INSERT,然后再运行SELECT查询并呈现表 .

    如果您更喜欢使用AJAX方法,我建议使用像https://datatables.net/这样的jQuery插件 . 然后在PHP中,您只需返回JSON编码的查询结果 .

相关问题