简体   繁体   English

无法发送 XMLHttpRequest

[英]Can't send XMLHttpRequest

I am trying to delete data with vanilla javascript ajax.我正在尝试使用 vanilla javascript ajax 删除数据。 After sending POST request with an id value to php file.将带有 id 值的 POST 请求发送到 php 文件后。 Every time it prints "error" in the console.每次它在控制台中打印“错误”。

HTML HTML

<div class="deleteButton" onclick="showAllert(this)" id="1">
  <i class="fa-solid fa-trash-can fa-2x" style="color:#A81E22" title="delete"></i>
</div>

JAVASCRIPT JAVASCRIPT

 <script>     
        function showAllert(a) {

            // sent delete request
            var dataId = a.getAttribute("id");
            var dataId = parseInt(dataId);

            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'includes/vehicles/del-veh.php', true);
            // xhr.responseType = 'json';
            xhr.onload = () => {
                if(xhr.status === 200) {
                    console.log(xhr.response);
                    location.reload();
                }else {
                    console.log("There was a problem");
                }
            }
            var data = JSON.stringify({id: dataId});
            xhr.send(data);
                    
        }
    </script>

PHP PHP

<?php
//Connection statement
require_once('../../Connections/ukcd.php');
$data = json_decode(file_get_contents('php://input'), true);

if(!empty($data["id"])) {
    // Required variables
    $vehid = $data['id'];
    echo "success";
}else {
    echo "error";
}

//AUTOEXECUTE METHOD
$delveh = $ukcd->prepare('DELETE FROM a_ukcd_client_vehicles WHERE clientveh_id = ?');
$result = $ukcd->execute($delveh, $vehid);

Send POST data in urlencoded format:以 urlencoded 格式发送 POST 数据:

 <script>     
        function showAllert(a) {

            // sent delete request
            var dataId = a.getAttribute("id");
            var dataId = parseInt(dataId);

            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'includes/vehicles/del-veh.php', true);
            // xhr.responseType = 'json';
            xhr.onload = () => {
                if(xhr.status === 200) {
                    console.log(xhr.response);
                    location.reload();
                }else {
                    console.log("There was a problem");
                }
            }
            // var data = JSON.stringify({id: dataId});
            xhr.send(`id=${dataId}`);
                    
        }
    </script>

And in your PHP script:在您的 PHP 脚本中:

<?php
//Connection statement
require_once('../../Connections/ukcd.php');
$id= $_POST['id'];

if(!empty($id)) {
    // Required variables
    $vehid = $id;
    echo "success";
}else {
    echo "error";
}

//AUTOEXECUTE METHOD
$delveh = $ukcd->prepare('DELETE FROM a_ukcd_client_vehicles WHERE clientveh_id = ?');
$result = $ukcd->execute($delveh, $vehid);

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

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