简体   繁体   English

无法通过 XMLHttpRequest 将数据从 php 页面发送到另一个 php 页面

[英]Can't Send data from php page to another php page via XMLHttpRequest

I have a table and each row has unique ID so I'm trying to send this ID to another PHP page to use this ID in SQL statement.我有一个表,每一行都有唯一的 ID,所以我试图将此 ID 发送到另一个 PHP 页面以在 SQL 语句中使用此 ID。 I've tried to do some echo statements to check if the request was successful but the echo statement wasn't executed我尝试做一些回显语句来检查请求是否成功但回显语句没有执行

Function which sends data发送数据的函数

<script>
    function promote(id) {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                alert("Promoted to QA successfully");
            }  
        };
        xhttp.open("GET", "promoteAccount.php?id="+id, true);
        xhttp.send();
    }
</script>

promoteAccount.php促进帐户.php

<?php
    $id = $_REQUEST['id'];
    require_once 'dbconnection.php';
    $sql = "SELECT * FROM staf WHERE StaffID = ".$id;
    $result = mysqli_query($conn, $sql);
    if ($result) {
        if ($row = mysqli_fetch_array($result)) {
            if ($row['Role'] == "Receptionist") {
                $updateSQL = "UPDATE staff SET Role = 'QA' WHERE StaffID = ".$id;
                $updateResult = mysqli_query($conn, $updateSQL);
            }
        }
    }
?>

As per the comment above regarding GET versus POST for operations of this nature I'd suggest that you alter the PHP to accept only a POST request and within your Javascript perhaps use the newer and far more powerful fetch api .根据上面关于 GET 与 POST 对于这种性质的操作的评论,我建议您将 PHP 更改为仅接受 POST 请求,并在您的 Javascript 中使用更新且功能更强大的fetch api It appears that the SQL can be simplifed so that you issue a single query using the column role within the where clause to verify the update is applicable rather than using a separate query and iterating through a recordset.似乎可以简化 SQL,以便您使用where子句中的列role发出单个查询来验证更新是否适用,而不是使用单独的查询并遍历记录集。

<?php
    
    if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['id'] ) ){
    
        require_once 'dbconnection.php';
        
        $code='QA';
        $role='Receptionist';
        # error: missing ` from after staffid!!
        $sql='update `staff` set `role`=? where `staffid`=? and `role`=?';
        $stmt=$conn->prepare( $sql );
        $stmt->bind_param('sss', $code, $_POST['id'], $role );
        $stmt->execute();
        $result=$stmt->affected_rows;
        $stmt->close();
        $conn->close();
        
        http_response_code( 200 );
        exit( $result==1 ? 'Success' : 'Failed' );
    }
    
    http_response_code( 404 );
    
    
?>

And the modified Javascript function using Fetch以及使用Fetch修改的 Javascript 函数

const promote=( id=false )=>{
    if( id ){
        let fd=new FormData();
            fd.set('id',id);
            
        fetch( 'promoteAccount.php',{ method:'post',body:fd } )
            .then(r=>r.text())
            .then(text=>{
                alert('Promoted to QA successfully');
                console.log( text );
            })
    }
}

The single page demo I created to test this:我创建的单页演示来测试这个:

<?php
    
    if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['id'] ) ){
    
        #require_once 'dbconnection.php';
        
        chdir('../../dbo');
        require 'db-conn-details.php';
        require 'mysqli-conn.php';
        
        
        
        $code='QA';
        $role='Receptionist';
        
        $sql='update `staff` set `role`=? where `staffid`=? and `role` = ?';
        
        $stmt=$conn->prepare( $sql );
        $stmt->bind_param('sss', $code, $_POST['id'], $role );
        
        $stmt->execute();
        $result=$stmt->affected_rows;
        
        $stmt->close();
        $conn->close();
        
        http_response_code( 200 );
        exit( $result==1 ? 'Success' : 'Failed' );
    }
    
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title></title>
    </head>
    <body>
        <input type='button' data-id=1 value='Promote 1' />
        <input type='button' data-id=2 value='Promote 2' />
        <input type='button' data-id=3 value='Promote 3' />
        <input type='button' data-id=4 value='Promote 4' />
        <input type='button' data-id=5 value='Promote 5' />
        <input type='button' data-id=6 value='Promote 6' />
        <input type='button' data-id=7 value='Promote 7' />
        <script>
            const promote=( id=false )=>{
                if( id ){
                    let fd=new FormData();
                        fd.set('id',id);
                        
                    fetch( 'promoteAccount.php',{ method:'post',body:fd } )
                        .then(r=>r.text())
                        .then(text=>{
                            alert('Promoted to QA successfully');
                            console.log( text );
                        })
                }
            }
            document.querySelectorAll('input[type="button"]').forEach( bttn=>bttn.addEventListener('click',(e)=>{
                promote( e.target.dataset.id );
            }))
        </script>
    </body>
</html>

Using the following table schema and data:使用下表架构和数据:

+---------+------------------+------+-----+---------+----------------+
| Field   | Type             | Null | Key | Default | Extra          |
+---------+------------------+------+-----+---------+----------------+
| staffid | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name    | varchar(50)      | NO   |     | 0       |                |
| role    | varchar(50)      | NO   |     | 0       |                |
+---------+------------------+------+-----+---------+----------------+



+---------+-----------+--------------+
| staffid | name      | role         |
+---------+-----------+--------------+
|       1 | Paula     | QA           |
|       2 | Daniela   | PA           |
|       3 | Susan     | Cleaner      |
|       4 | Isobel    | Receptionist |
|       5 | Carrie    | Team Leader  |
|       6 | Chantelle | IT support   |
|       7 | Helen     | Receptionist |
+---------+-----------+--------------+

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM