简体   繁体   English

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

[英]How do I use AJAX to refresh a database table after a new row is entered via form submit?

Long time reader, first question. 长期的读者,第一个问题。 I should note that I am a beginner. 我应该注意我是一个初学者。

My page displays a discography of records. 我的页面显示记录的唱片目录。 It has two parts: 1. A form to enter a new row into the records table. 它包括两个部分:1.一种在records表中输入新行的表单。 2. The records table echoed from the database. 2. records表从数据库中回显。

Currently, a user can fill out the form, click "submit" and the new row is INSERTed into the records table. 当前,用户可以填写表单,单击“提交”,然后将新行插入到records表中。

I want to use AJAX so that the records table is automatically refreshed when the form's submit button is clicked. 我想使用AJAX,以便在单击表单的“提交”按钮时自动刷新records表。

I'll post shortened versions of the code below. 我将在下面发布缩短版本的代码。

The form is already submitted via AJAX with this code (I got from a tutorial): 该表单已经通过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.');
            }
        });
    });
});

Here is the HTML: 这是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>

Here is the PHP for form action (formInsert.php): 这是用于表单操作的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>'; 
} 

And finally here is the dataTable.php. 最后是dataTable.php。 This is what I want to be updated automatically via AJAX when the "submit" button is pressed. 这是我想在按下“提交”按钮时通过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>

I really appreciate you making it this far! 我真的很感谢您能做到这一点! Is there anyway to use AJAX (or update the current AJAX) to refresh the table when the submit button is clicked for a new row INSERT? 无论如何,单击提交按钮以插入新行INSERT时,是否可以使用AJAX(或更新当前的AJAX)刷新表?

You are currently rendering the table server side and updating it via AJAX would modify the table and render the new row client side. 您当前正在渲染表服务器端,并且通过AJAX更新它会修改表并渲染新行客户端。 It can be done, but I strongly recommend doing it all the same way. 可以做到,但我强烈建议您采用相同的方式。

The simplest approach given your existing code, is to simply post the insert fields to the same page. 给定现有代码,最简单的方法是将插入字段发布到同一页面。 Then check the POST data and perform the INSERT as needed before running the SELECT query and rendering the table. 然后在运行SELECT查询和呈现表之前,检查POST数据并根据需要执行INSERT。

If you prefer to go with an AJAX approach I recommend using a jQuery plugin like https://datatables.net/ . 如果您喜欢使用AJAX方法,建议您使用https://datatables.net/之类的jQuery插件。 Then in PHP you would simply return the JSON encoded query results. 然后在PHP中,您只需返回JSON编码的查询结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何提交表单并使用 php 在 mysql 数据库表中插入新行? - How can I submit a form and use php to insert a new row into a mysql database table? 如何通过以下方式提交表单:PHP发送电子邮件,使用Ajax进行屏幕刷新,然后在不进行屏幕刷新的情况下在表单旁边发布消息? - How do I submit form via: PHP sending email, Using Ajax for no screen refresh, and post a message next to form with no screen refresh? 如何刷新表格数据Ajax表单提交? - How to refresh table data ajax form submit? 表单提交后不刷新即可向表中添加行-jQuery Ajax PHP - Add row to table after a form submit without refresh - jquery ajax php 由ajax在laravel中提交的简单表单,然后将新行与已提交表单中的数据一起插入到现有表中 - simple form submit by ajax in laravel and after, insert new row into existing table with data from submited form 在JQuery Ajax验证后如何提交表单? - How do I submit a form after JQuery Ajax validation? 为什么我必须单击刷新按钮才能在提交后从数据库中获取新数据 - Why do I have to click refresh button to get new data from database after submit 如何使用PDO将表单值提交到数据库? - How do I use PDO to submit form values to a database? 如何同时使用验证码ajax php和验证? 当我提交表格时,不能刷新 - how to use captcha ajax php and validation together? When i submit the form it must not refresh 提交Ajax表单后刷新页面 - Refresh page after ajax form submit
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM