简体   繁体   中英

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. 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
    $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 . 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.

<?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

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 |
+---------+-----------+--------------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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