使用ajax问题传递PHP变量

时间:2016-01-02 15:11:35

标签: php ajax

我想将包含订单ID和客户ID的php变量用javascript传递给php文件但是当我使用var dump来检查数据时php返回(string(43)“”)

以下代码我尝试传递变量:

带有html代码的PHP文件和调用js函数的按钮:

while ($orders = mysqli_fetch_array($orderList)) {
    $orderId        = $orders['order_id'];
    $CustId         = $orders['car_id'];
    $orderPrice     = $orders['order_price'];
    $orderStatus    = $orders['order_state'];
    $orderDate      = $orders['order_date'];
    $trackId        = $orders['track_id'];

    echo "<tr>
        <td>" . $sr++ . "</td>
        <td>$orderId</td>
        <td>$trackId</td>
        <td>$CustId</td>
        <td>$orderStatus</td>
        <td>$orderPrice</td>
        <td>$orderDate</td>
        <td class='btn-group-horizontal'>
        <a href='order-details.php?action=view&order_id=$orderId&cust_id=$CustId' title='View Order or Edit Order'><i class='btn btn-info fa fa-eye'></i></a>
        <a href='order-details.php?action=view&order_id=$orderId&cust_id=$CustId' title='Edit Order'><i class='btn btn-primary fa fa-pencil'></i></a>
        <a href='#' title='Delete Order'><i class='btn btn-danger fa fa-trash-o'></i></a>
        <button type='button' onclick='backendDeleteOrder();'>Delete</button>
        </td>
        </tr>";
}

JS代码传递PHP变量:

function backendDeleteOrder(){

    var hr = new XMLHttpRequest();
    // Create some variables we need to send to our PHP file
    var url = "functions/delete.php?action=backendDeleteOrder";
    var orderID = "<?php echo $orderId;?>";
    var custId = "<?php echo $CustId;?>";

    var vars = "orderID=" + orderID + "&custId=" + custId;
    hr.open("POST", url, true);
    // Set content type header information for sending url encoded variables in the request
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = function() {
        if(hr.readyState === 4 && hr.status === 200) {
            var return_data = hr.responseText;
            document.getElementById("statusOrder").innerHTML = return_data;
            window.scrollTo(0,0);
        }
    }
    // Send the data to PHP now... and wait for response to update the status div
    hr.send(vars); // Actually execute the request
    document.getElementById("statusOrder").innerHTML = "Processing...! Please Wait.";
}

接收js数据的PHP文件:

// I also tried POST here like.
//$action = isset($_POST['action']) ? $_POST['action'] : "";

$action = isset($_GET['action']) ? $_GET['action'] : "";

if ($action == 'backendDeleteOrder') {
    $orderId = $db->real_escape_string($_POST['orderID']);
    $custId = $db->real_escape_string($_POST['custId']);

    var_dump($custId.$orderId);
}

如何解决这个问题?

0 个答案:

没有答案