Table of Contents
Limitations and misunderstandings of traditional form submission
AJAX for asynchronous data processing
Implement AJAX request processing: front-end part
1. HTML structure and data properties
2. JavaScript processing logic
Implement AJAX request processing: backend PHP part (accept-requests.inc.php)
Style Beautification (CSS)
Summary and best practices
Home Web Front-end HTML Tutorial PHP dynamic data interaction: optimize form submission and database operations through AJAX

PHP dynamic data interaction: optimize form submission and database operations through AJAX

Sep 01, 2025 pm 03:12 PM

PHP dynamic data interaction: optimize form submission and database operations through AJAX

This article discusses methods for efficient handling of dynamic data updates in web applications, especially for "accept" or "reject" operations in tables. By analyzing the limitations of traditional form submission, we recommend using AJAX technology to implement asynchronous requests, thereby avoiding page refresh and improving user experience. The tutorial will show in detail how to safely pass the operation type and data ID to the backend PHP script for database operations using HTML5 data-* attributes and JavaScript fetch API.

Limitations and misunderstandings of traditional form submission

When building dynamic web applications, we often need to handle users' operations on a row of data in the list, such as accepting or rejecting a request. A common misunderstanding is to try to "define" the _POST variable by $_POST['request_id'] = $requests[$j]['request_id']; when PHP generates HTML. This approach is invalid because the _POST hyperglobal variable is populated after the HTTP POST request is received and parsed by the server, rather than manually assigning values ​​when the page is generated. When the form is actually submitted, these manually assigned variables will no longer exist.

Although the traditional form submission method (

) can implement data submission, it will cause the following problems for scenarios where multiple rows of data are required to operate independently:
  1. Page refresh: Each submission will cause the entire page to reload and interrupt the user experience.
  2. Complexity: If each row has an independent form, it will cause redundancy in the DOM structure; if all operations share a form, complex logic is required to distinguish which row is operated.
  3. Not smooth: Frequent page refresh will reduce work efficiency when the user performs multiple operations.

AJAX for asynchronous data processing

In order to overcome the limitations of traditional form submission, modern web development generally adopts asynchronous JavaScript and XML (AJAX) technologies. AJAX allows clients to exchange data with the server without reloading the entire page. This provides users with a smoother and faster interactive experience.

AJAX has a particularly obvious advantage in handling acceptance/rejection scenarios for list data:

  • The page remains unchanged after the user clicks the button.
  • Only the necessary data is sent to the server.
  • After the server processes it, the results (such as success, failure, and updated data) can be returned to the client, and the client then partially updates the page according to the results.

Implement AJAX request processing: front-end part

We will use an example to demonstrate how to handle acceptance/denied requests in a table using AJAX.

1. HTML structure and data properties

First, we need to prepare the necessary information for each row of data and its operation buttons when PHP generates HTML. The key point is:

  • Remove the tag: Since we will use JavaScript to send requests, the traditional HTML
    tag is no longer needed.
  • Line ID: Set request_id to the id attribute of the element to facilitate JavaScript acquisition.
  • Data type attribute: Use HTML5 data-* attributes (such as data-type='accept' or data-type='deny') to mark the operation type of a button.
  • Here is the sample code for PHP to generate table rows:

     <?php for ($j = 0; $j < count($requests); $j): ?>
        <tr id="'<?php" echo>' class="table-row">
            <?php //Set the text according to the request type if ($requests[$j][&#39;request_type&#39;] == &#39;1&#39;) {
                    $request_type = &#39;candidate&#39;;
                } else {
                    $request_type = &#39;voter&#39;;
                } 
            ?>
            <td class="school">=$request_type?></td>
            <td class="name">=$requests[$j]['first_name']?></td>
            <td class="candidates">=$requests[$j]['last_name']?></td>
            <td> 
                <button data-type="'accept'" name="acceptReq" value="req_accepted" type="button" class="btn btn-success">Accept</button> 
            </td>
            <td> 
                <button data-type="'deny'" name="denyReq" value="req_denied" type="button" class="btn btn-danger">Deny</button> 
            </td>
        </tr>
    <?php endfor; ?>

    Note: The type property of the button should be set to button to prevent its default commit behavior.

    2. JavaScript processing logic

    Next, we use JavaScript to listen for button click events and send an AJAX request. Here we use the modern fetch API.

     <script>
        // Create a FormData object to build a POST request body let fd = new FormData();
    
        // Select all buttons with name="acceptReq" or name="denyReq" document.querySelectorAll(&#39;button[name="acceptReq"],button[name="denyReq"]&#39;).forEach(bttn => {
            bttn.addEventListener(&#39;click&#39;, function(e) {
                // Block the default behavior of buttons (this will prevent form submission if type is not a button)
                e.preventDefault(); 
    
                // Get the parent <tr> element of the currently clicked button let tr = this.parentNode.closest(&#39;tr&#39;);
    
                // Get request_id from the id attribute of <tr>
                fd.set(&#39;id&#39;, tr.id.trim()); // Use trim() to clear possible spaces // Get the operation type fd.set(&#39;type&#39;, this.dataset.type);
    
                // Send POST request using fetch API fetch(&#39;../assets/php/accept-requests.inc.php&#39;, { 
                    method: &#39;post&#39;, 
                    body: fd // Use FormData object as request body})
                .then(r => {
                    if (!r.ok) { // Check the HTTP response status code throw new Error(`HTTP error! status: ${r.status}`);
                    }
                    return r.text(); // parse the response as text})
                .then(text => {
                    // The callback function alert(text); // The message returned by the server pops up // TODO: Here, update the DOM according to the server response, such as removing the line // tr.remove();
                })
                .catch(e => {
                    // Capture errors in request or response processing console.error(&#39;Request failed:&#39;, e);
                    alert(&#39;The operation failed, please try again.&#39;);
                });
            });
        });
    </script>

    JavaScript code detailed explanation:

    • FormData(): is used to build a request body in the form of key-value pairs, which is very suitable for sending form data.
    • document.querySelectorAll(): Select all Accept and Reject buttons on the page.
    • forEach() and addEventListener(): Add a click event listener for each button.
    • e.preventDefault(): Blocks the default behavior of the button and ensures that the request is sent by JavaScript control.
    • this.parentNode.closest('tr'): this points to the currently clicked button. parentNode gets its parent element , closest('tr') looks upward to the nearest ancestor element, thus getting the row containing request_id.
    • tr.id.trim(): Gets the id attribute value of and uses trim() to remove possible whitespace characters.
    • this.dataset.type: Gets the value of the data-type attribute on the button.
    • fetch(): Send HTTP request.
      • method: 'post': Specify the request method to POST.
      • body: fd: Send the FormData object as the request body.
    • .then(): The successful response to processing the fetch request. The first .then() checks the HTTP status, and the second .then() handles the response body content.
    • .catch(): Captures network errors that may occur during the request process or other errors in the Promise chain.
    • DOM Update (TODO): In actual applications, after successfully processing the request, you usually write code here to update the UI, such as removing accepted/rejected rows from the table, or updating the status display of rows.
    • Implement AJAX request processing: backend PHP part (accept-requests.inc.php)

      On the server side (for example, the ../assets/php/accept-requests.inc.php file), you need to write PHP code to receive data sent by AJAX requests and perform the corresponding database operations.

       <?php // Make sure to process only POST requests if ($_SERVER[&#39;REQUEST_METHOD&#39;] === &#39;POST&#39;) {
          // Get the data sent by the front end $requestId = $_POST[&#39;id&#39;] ?? null;
          $actionType = $_POST[&#39;type&#39;] ?? null;
      
          // Verify data if ($requestId === null || $actionType === null) {
              http_response_code(400); // Bad Request
              echo "Error: Missing request ID or operation type.";
              exit();
          }
      
          // Database connection (please replace it with your actual database connection code)
          $servername = "localhost";
          $username = "username";
          $password = "password";
          $dbname = "your_database";
      
          try {
              $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
              $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      
              $responseMessage = "";
      
              switch ($actionType) {
                  case 'accept':
                      // Execute acceptance logic, such as updating the status or deleting the request $stmt = $conn->prepare("DELETE FROM requests WHERE request_id = :id");
                      $stmt->bindParam(':id', $requestId, PDO::PARAM_INT);
                      $stmt->execute();
                      $responseMessage = "Request{$requestId} is accepted and deleted.";
                      break;
                  case 'deny':
                      // Execute rejection logic, such as updating status or deleting request $stmt = $conn->prepare("DELETE FROM requests WHERE request_id = :id");
                      $stmt->bindParam(':id', $requestId, PDO::PARAM_INT);
                      $stmt->execute();
                      $responseMessage = "Request{$requestId} has been rejected and deleted.";
                      break;
                  default:
                      http_response_code(400); // Bad Request
                      echo "Error: Invalid operation type.";
                      exit();
              }
      
              echo $responseMessage; // Return the success message to the front end} catch (PDOException $e) {
              http_response_code(500); // Internal Server Error
              echo "Database operation failed: ". $e->getMessage();
          } finally {
              $conn = null; // Close database connection}
      
      } else {
          http_response_code(405); // Method Not Allowed
          echo "Only POST requests are allowed.";
      }
      ?>

      Detailed explanation of PHP code:

      • $_SERVER['REQUEST_METHOD']: Ensure that only POST requests can enter the processing logic.
      • $_POST['id'] and $_POST['type']: PHP will automatically parse data sent by FormData and access it through $_POST hyperglobal variable.
      • Data Verification: Before processing data, be sure to verify that request_id and actionType exist and are effective, which is a basic requirement for security and robustness.
      • Database operations: Use PDO for database connection and operation. It is recommended to use preprocessing statements (prepare and bindParam) to prevent SQL injection attacks.
      • switch statement: execute different business logic (accept or reject) based on the value of actionType.
      • Response: Return the processing result (such as success message or error message) to the front end via echo.
      • HTTP status code: Setting the appropriate HTTP status code (such as 200 OK, 400 Bad Request, 500 Internal Server Error, 405 Method Not Allowed) helps the front-end better understand the server response.

      Style Beautification (CSS)

      To provide better visual feedback, some CSS styles can be added, such as mouseover effects.

       *{
        transition:ease-in-out all 100ms;
        font-family:monospace
      }
      th{
        background:rgba(50,50,100,0.5);
        color:white;
      }
      tr{
        margin:0.25rem;
      }
      tr:hover td{
        background:rgba(0,200,0,0.25);
      }
      td,
      th{
        margin:0.25rem;
        border:1px dotted rgba(0,0,0,0.3);
        padding:0.45rem
      }
      button:hover{
        cursor:pointer;
      }
      [data-type='accept']:hover{
        background:lime
      }
      [data-type='deny']:hover{
        background:red;
        color:white;
      }

      Summary and best practices

      Through this tutorial, we learned how to use AJAX technology, especially the fetch API, to optimize dynamic data interaction in web applications. This method not only improves the user experience, but also makes the logic separation between the front-end and the back-end clearer.

      Key points review:

      • Avoid manually setting $_POST: $_POST is automatically populated when the server resolves the request.
      • * Use `data- ` attribute: ** Store small data related to elements in HTML, which is convenient for JavaScript to obtain.
      • AJAX (fetch API): Implement asynchronous requests to avoid page refresh.
      • FormData object: Conveniently construct POST request body.
      • Backend PHP processing: receive $_POST data, perform database operations, and return a response.
      • Security: Always verify and filter all user input, using preprocessing statements to prevent SQL injection.
      • User feedback: Provide loading instructions during the AJAX request, and give clear feedback after the request succeeds or fails (such as message prompts, DOM updates).

      By following these principles, you can build more efficient, user-friendly web applications.

The above is the detailed content of PHP dynamic data interaction: optimize form submission and database operations through AJAX. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

How to add an icon to your website title tab in HTML How to add an icon to your website title tab in HTML Aug 07, 2025 pm 11:30 PM

To add an icon to the website title bar, you need to link a favicon file in part of the HTML. The specific steps are as follows: 1. Prepare a 16x16 or 32x32 pixel icon file. It is recommended to use favicon.ico to name it and place it in the website root directory, or use modern formats such as PNG and SVG; 2. Add link tags to HTML, such as PNG or SVG formats, adjust the type attribute accordingly; 3. Optionally add high-resolution icons for mobile devices, such as AppleTouchIcon, and specify different sizes through the sizes attribute; 4. Follow best practices, place the icon in the root directory to ensure automatic detection, clear the browser cache after update, and check the correctness of the file path.

Why is my HTML image not showing up? Why is my HTML image not showing up? Aug 16, 2025 am 10:08 AM

First, check whether the src attribute path is correct, and ensure that the relative or absolute path matches the HTML file location; 2. Verify whether the file name and extension are spelled correctly and case-sensitive; 3. Confirm that the image file actually exists in the specified directory; 4. Use appropriate alt attributes and ensure that the image format is .jpg, .png, .gif or .webp widely supported by the browser; 5. Troubleshoot browser cache issues, try to force refresh or directly access the image URL; 6. Check server permission settings to ensure that the file can be read and not blocked; 7. Verify that the img tag syntax is correct, including the correct quotes and attribute order, and finally troubleshoot 404 errors or syntax problems through the browser developer tool to ensure that the image is displayed normally.

How to use the HTML abbr tag for abbreviations How to use the HTML abbr tag for abbreviations Aug 05, 2025 pm 12:54 PM

Using HTML tags can improve the accessibility and clarity of content; 1. Mark abbreviations or acronyms with abbreviations; 2. Add title attributes to unusual abbreviations to provide a complete explanation; 3. Use when the document first appears, avoiding duplicate annotations; 4. You can customize the style through CSS, and the default browser usually displays dotted underscores; 5. It helps screen reader users understand terms and enhance user experience.

How to add an icon to a button in HTML How to add an icon to a button in HTML Aug 07, 2025 pm 11:09 PM

Using FontAwesome can quickly add icons by introducing CDN and adding icon classes to buttons, such as Like; 2. Using labels to embed custom icons in buttons, the correct path and size must be specified; 3. Embed SVG code directly to achieve high-resolution icons and keep them consistent with the text color; 4. Spacing should be added through CSS and aria-label should be added to the icon buttons to improve accessibility; in summary, FontAwesome is most suitable for standard icons, pictures are suitable for custom designs, while SVG provides the best scaling and control, and methods should be selected according to project needs. FontAwesome is usually recommended.

How to use the bdo tag to override text direction in HTML How to use the bdo tag to override text direction in HTML Aug 16, 2025 am 09:32 AM

Thebdotagisusedtooverridethebrowser’sdefaulttextdirectionrenderingwhendealingwithmixedleft-to-rightandright-to-lefttext,ensuringcorrectvisualdisplaybyforcingaspecificdirectionusingthedirattributewithvalues"ltr"or"rtl",asdemonstrat

Extract nested URLs from dynamic web pages using R language: httpr and API interaction practice Extract nested URLs from dynamic web pages using R language: httpr and API interaction practice Aug 27, 2025 pm 07:06 PM

This tutorial explores the problem of crawling failure if JavaScript dynamically loads content when crawling URLs from web pages using the R language rvest package. The article explains in detail why traditional HTML parsing methods may be invalid and provides an efficient solution: by identifying and directly calling the API interface behind the web page, using the httr package to obtain JSON data, thereby successfully extracting the required information.

What is the difference between HTML id and class What is the difference between HTML id and class Aug 07, 2025 am 12:03 AM

The id must be unique. One id in each page can only be used for one element, and the class can be reused on multiple elements, and one element can have multiple classes; 2. Scenarios using id include: positioning a single specific element, link anchors within the page, JavaScript operates elements through id, and labels associated with form elements; scenarios using class include: applying the same style or behavior to multiple elements, building reusable UI components, and selecting multiple elements in JavaScript; 3. In CSS, targeting is done by #id selector and .class selector respectively, getElementById() is used for id, getEleme

How to highlight text with the  tag? How to highlight text with the tag? Aug 04, 2025 pm 04:29 PM

Use tags to highlight text semantically, often used to identify search results or important content; 2. Custom styles such as background colors, text colors and borders can be customized through CSS; 3. It should be used in contexts with practical significance, rather than just visual decoration to improve accessibility and SEO effects.

See all articles