Home Backend Development PHP Problem How to realize real-time modification of php html table

How to realize real-time modification of php html table

Apr 19, 2023 am 10:05 AM

In web development, tables are a very commonly used element. In tables, we often need to modify the data in it. The usual way is to update the data through back-end processing. But if we want to directly modify the table data in real time on the front end, how to achieve it? This article will introduce how to realize real-time modification of table data through AJAX technology in PHP and HTML pages.

1. Overview

In this article, we will illustrate through an example of real-time modification of a simple form. First, we need to generate a form using PHP code. As shown below:

<!DOCTYPE html>
<html>
<head>
    <title>Table Example</title>
    <meta charset="utf-8">
</head>
<body>
    <?php 
        $data = array(
            array("姓名","性别","年龄"),
            array("张三","男","20"),
            array("李四","女","22"),
            array("王五","男","21")
        );
    ?>
    
    <table border="1" cellpadding="5">
        <?php 
            foreach($data as $row) {
                echo "<tr>";
                foreach($row as $cell) {
                    echo "<td>$cell</td>";
                }
                echo "</tr>";
            }
        ?>
    </table>
</body>
</html>
Copy after login

The above code generates a simple table containing the name, gender and age information of four people. In PHP, we can use arrays to represent data in tables.

2. Modify the table data in real time

Now, what we want to achieve is to modify the data in the table in real time. We can achieve this through the following steps:

  1. Add a modify button to the table.

In the last column of the data in each row, add a button to modify the data in that row. Use the following code:

foreach($data as $row) {
    echo "<tr>";
    foreach($row as $i => $cell) {
        if($i==count($row)-1) {
            echo "<td><button onclick=&#39;editRow(event)&#39;>修改</button></td>";
        }
        else {
            echo "<td>$cell</td>";
        }
    }
    echo "</tr>";
}
Copy after login

A JavaScript function editRow is used here to be called when the modify button is clicked.

  1. Write JavaScript function editRow.

Add the following JavaScript code to the HTML page:

<script>
    function editRow(event) {
        // 获取当前点击按钮所在行以及行内的数据
        var row = event.target.parentNode.parentNode;
        var cells = row.getElementsByTagName("td");
        var data = [];
        for(var i=0;i<cells.length-1;i++) {
            data.push(cells[i].innerText);
        }
        
        // 将数据填入表单中
        var form = "<form>";
        form += "<input type=&#39;hidden&#39; name=&#39;row&#39; value=&#39;"+row.rowIndex+"&#39;>";
        form += "<input type=&#39;text&#39; name=&#39;name&#39; value=&#39;"+data[0]+"&#39;>";
        form += "<input type=&#39;text&#39; name=&#39;gender&#39; value=&#39;"+data[1]+"&#39;>";
        form += "<input type=&#39;text&#39; name=&#39;age&#39; value=&#39;"+data[2]+"&#39;>";
        form += "<button type=&#39;button&#39; onclick=&#39;saveChanges(event)&#39;>保存</button>";
        form += "</form>";
        
        // 将表单替换为数据输入框
        row.innerHTML = form;
    }
</script>
Copy after login

A function editRow is defined here. When the modify button is clicked, the function will edit the current row The data is displayed as a form, which is convenient for users to modify.

  1. Write JavaScript function saveChanges.

After entering the data in the form, we need to send the modified data to the server through AJAX technology and update the form. Now, we need to write the JavaScript function saveChanges to save the modified data. This function uses the following code:

<script>
    function saveChanges(event) {
        // 获取当前修改的数据
        var form = event.target.parentNode;
        var rowIndex = form.row.value;
        var name = form.name.value;
        var gender = form.gender.value;
        var age = form.age.value;
        var data = "rowIndex="+rowIndex+"&name="+name+"&gender="+gender+"&age="+age;
        
        // 发送 AJAX 请求
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if(xmlhttp.readyState==4 && xmlhttp.status==200) {
                // 更新表格数据
                var row = form.parentNode;
                row.innerHTML = xmlhttp.responseText;
            }
        };
        xmlhttp.open("POST","update.php",true);
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send(data);
    }
</script>
Copy after login

This function sends a POST request to the server's update.php page through the XMLHttpRequest object to handle the update operation of table data. . After the data update is processed on the server side, new table data will be returned, and the table data can be obtained and updated through xmlhttp.responseText.

  1. Write server-side code

On the server side, we need to write a update.php page to handle the update operation of table data . The code of this page is as follows:

<?php
    // 获取 POST 数据
    $rowIndex = $_POST["rowIndex"];
    $name = $_POST["name"];
    $gender = $_POST["gender"];
    $age = $_POST["age"];
    
    // 将新的数据返回给客户端
    $data = array(
        array("姓名","性别","年龄"),
        array($name,$gender,$age)
    );
    
    $table = "<table border=&#39;1&#39; cellpadding=&#39;5&#39;>";
    foreach($data as $row) {
        $table .= "<tr>";
        foreach($row as $cell) {
            $table .= "<td>$cell</td>";
        }
        $table .= "</tr>";
    }
    $table .= "</table>";
    
    echo $table;
?>
Copy after login

This page receives the modified data passed by the client through POST, then updates the data and returns the updated data to the client.

Now, we have completed the process of real-time modification of the entire form. Open the page in the browser, click the modify button, enter the modified data in the pop-up input box, and click the save button to see the effect of the data update.

3. Summary

This article introduces how to realize real-time modification of table data through AJAX technology in PHP and HTML pages. Among them, we use PHP to generate a simple form, use JavaScript to implement real-time modification of the table data, and send the modified data to the server for processing through AJAX. This method can help us operate tabular data more conveniently and quickly. However, it should be noted that in actual development, in order to ensure the security and correctness of data, we need to strictly verify and filter the received data to prevent malicious attacks and data misoperation.

The above is the detailed content of How to realize real-time modification of php html table. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. Mar 25, 2025 am 10:37 AM

PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

PHP Secure File Uploads: Preventing file-related vulnerabilities. PHP Secure File Uploads: Preventing file-related vulnerabilities. Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP Authentication & Authorization: Secure implementation. PHP Authentication & Authorization: Secure implementation. Mar 25, 2025 pm 03:06 PM

The article discusses implementing robust authentication and authorization in PHP to prevent unauthorized access, detailing best practices and recommending security-enhancing tools.

What is the purpose of prepared statements in PHP? What is the purpose of prepared statements in PHP? Mar 20, 2025 pm 04:47 PM

Prepared statements in PHP enhance database security and efficiency by preventing SQL injection and improving query performance through compilation and reuse.Character count: 159

PHP Encryption: Symmetric vs. asymmetric encryption. PHP Encryption: Symmetric vs. asymmetric encryption. Mar 25, 2025 pm 03:12 PM

The article discusses symmetric and asymmetric encryption in PHP, comparing their suitability, performance, and security differences. Symmetric encryption is faster and suited for bulk data, while asymmetric is used for secure key exchange.

How do you retrieve data from a database using PHP? How do you retrieve data from a database using PHP? Mar 20, 2025 pm 04:57 PM

Article discusses retrieving data from databases using PHP, covering steps, security measures, optimization techniques, and common errors with solutions.Character count: 159

PHP API Rate Limiting: Implementation strategies. PHP API Rate Limiting: Implementation strategies. Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

See all articles