Hello every body.
I have a project where I output a table to an html page. This table outputs data from JSON, but in the last column I output two buttons.
The first one should open a menu to edit this unit and the second one should delete it.
I am using the POST method in JS to get the ID. Then I pass it to php which should perform the deletion and run the following php code which will overwrite the JSON with the changed data.
When I click on Delete, the following is output in the console:
The delete button is pressed
table-units.js:133 deleted item ID: 3
table-units.js:138 URL to delete: ../PHP/vendor/delete_unit.php
update occurs, the console outputs overwritten data, but nothing changes in the table.
The table changes itself without refreshing the page, but even when refreshing without results.
Everything remains in its place, as well as in the database does not happen.
here are my JS and PHP codes
Translated with DeepL.com (free version)
var xhr = new XMLHttpRequest();
var url = "../JSON/db.json";
xhr.open("GET", url, true);
xhr.onload = function () {
if (xhr.status === 200) {
var dataArray = JSON.parse(xhr.responseText);
var outputTable = document.getElementById("output");
var tableHeader = "<thead><tr><th></th><th>ID</th><th>Owner</th><th>Name</th><th>Status</th><th>Dimensions</th><th>Type</th><th>Capacity</th><th>Location</th><th>Notes</th><th>Edit</th></tr></thead>";
outputTable.innerHTML = tableHeader;
var tableRows = "";
dataArray.forEach(function (data, index) {
if (index < 10) {
var tableRow = "<tr>";
var st_available = data.available == "1" ? "<i class='bx bx-circle'></i>" : "<i class='bx bx-chevron-down-circle'></i>";
var dr_status = data.status == "US_Citizen" ? "US Citizen" : (data.status == "green_card" ? "Green Card" : (data.status == "work_autorization" ? "Work Autorization" : "No Border"));
var truck_type = data.truck_type == "largestraight" ? "Large Straight" : (data.truck_type == "smallstraight" ? "Small Straight" : (data.truck_type == "sprinter" ? "Sprinter" : "Unknown"));
tableRow +=
"<th id='available'>" + st_available + "</td>" +
"<th id='owner'>" + data.id + "</td>" +
"<th id='name'>" + data.owner_id + "</td>" +
"<th id='status'>" + data.name + "</td>" +
"<th id='dimensions'>" + dr_status + "</td>" +
"<th id='type'>" + data.dimensions + "</td>" +
"<th id='capacity'>" + truck_type + "</td>" +
"<th id='location'>" + data.capacity + "</td>" +
"<th id='location'>" + data.location_name + "</td>" +
"<th id='notes'>" + data.notes + "</td>" +
"<th id='edit'>" +
"<div class='edit'>" +
"<i class='bx bx-edit'></i>" +
"</div>" +
"<div class='delete' data-id='" + data.id + "'>" +
"<i class='bx bx-checkbox-minus'></i>" +
"</div>" +
"</th>";
tableRow += "</tr>";
tableRows += tableRow;
}
});
outputTable.innerHTML += "<tbody>" + tableRows + "</tbody>";
var paginationContainer = document.getElementById("pagination");
var totalPages = Math.ceil(dataArray.length / 10);
for (var i = 1; i <= totalPages; i++) {
var pageButton = document.createElement("div");
pageButton.classList.add("btn-contaier");
pageButton.classList.add("page");
pageButton.textContent = i;
pageButton.addEventListener("click", function () {
var pageNum = parseInt(this.textContent);
var startIndex = (pageNum - 1) * 10;
var endIndex = startIndex + 10;
var tableRows = "";
dataArray.slice(startIndex, endIndex).forEach(function (data) {
var tableRow = "<tr>";
var st_available = data.available == "1" ? "<i class='bx bx-circle'></i>" : "<i class='bx bx-chevron-down-circle'></i>";
var dr_status = data.status == "US_Citizen" ? "US Citizen" : (data.status == "green_card" ? "Green Card" : (data.status == "work_autorization" ? "Work Autorization" : "No Border"));
var truck_type = data.truck_type == "largestraight" ? "Large Straight" : (data.truck_type == "smallstraight" ? "Small Straight" : (data.truck_type == "sprinter" ? "Sprinter" : "Unknown"));
tableRow +=
"<th id='available'>" + st_available + "</td>" +
"<th id='owner'>" + data.id + "</td>" +
"<th id='name'>" + data.owner_id + "</td>" +
"<th id='status'>" + data.name + "</td>" +
"<th id='dimensions'>" + dr_status + "</td>" +
"<th id='type'>" + data.dimensions + "</td>" +
"<th id='capacity'>" + truck_type + "</td>" +
"<th id='location'>" + data.capacity + "</td>" +
"<th id='location'>" + data.location_name + "</td>" +
"<th id='notes'>" + data.notes + "</td>" +
"<th id='edit'>" +
"<div class='edit'>" +
"<i class='bx bx-edit'></i>" +
"</div>" +
"<div class='delete' data-id='" + data.id + "'>" +
"<i class='bx bx-checkbox-minus'></i>" +
"</div>" +
"</th>";
tableRow += "</tr>";
tableRows += tableRow;
});
outputTable.querySelector("tbody").innerHTML = tableRows;
});
paginationContainer.querySelector(".pages").appendChild(pageButton);
}
outputTable.addEventListener("click", function(event) {
var target = event.target;
if (target.classList.contains("delete")) {
console.log("Кнопка delete нажата");
var unitId = target.dataset.id;
console.log("ID удаляемого элемента:", unitId);
// Отправляем запрос на сервер для удаления записи
var deleteRequest = new XMLHttpRequest();
var deleteUrl = "../PHP/vendor/delete_unit.php";
console.log("URL для удаления:", deleteUrl);
deleteRequest.open("POST", deleteUrl, true);
deleteRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
deleteRequest.onload = function() {
console.log("Request ended");
if (deleteRequest.status === 200) {
console.log("Deleted:", deleteRequest.responseText);
location.reload();
} else {
// Ошибка при удалении
console.error("Error with deleting");
console.error(deleteRequest.statusText);
}
};
deleteRequest.onerror = function() {
console.error("Network error");
};
var requestData = "id=" + encodeURIComponent(unitId);
deleteRequest.send(requestData);
}
});
}
};
xhr.send();
PHP for delete unit:
<?php
// Подключаемся к базе данных
include 'connect.php';
// Получаем значение 'id' из POST-запроса
$db_id = $_POST['id'];
// Защита от SQL инъекций
$db_id = mysqli_real_escape_string($connect, $db_id);
// Выполняем SQL-запрос для удаления записи с указанным id
$query = "DELETE FROM `units` WHERE `id` = '$db_id'";
$result = mysqli_query($connect, $query);
// Проверяем успешность выполнения запроса
if ($result) {
echo "Запись успешно удалена.";
// Запускаем скрипт get_units_array.php
include 'get_units_array.php';
} else {
echo "Ошибка при удалении записи: " . mysqli_error($connect);
}
// Закрываем соединение с базой данных
mysqli_close($connect);
?>
PHP for update JSON here you go.
<?php
include 'connect.php';
function getLocationDetails($zipcode) {
$access_token = 'pk.eyJ1IjoiNDEyZDQxMmRhMTIzIiwiYSI6ImNsdm1laHF3cDAxdGUybHFvcW82ajB6eHUifQ.NSwloMttXhtT1prPnzYaxQ';
$url = "https://api.mapbox.com/geocoding/v5/mapbox.places/$zipcode.json?country=US&access_token=$access_token";
$response = file_get_contents($url);
if ($response === FALSE) {
return "Error with Mapbox API";
}
$data = json_decode($response, true);
if ($data && isset($data['features'][0]['center'])) {
$center = $data['features'][0]['center'];
return implode(', ', $center);
} else {
return "Местоположение не найдено";
}
}
function getLocationName($zipcode) {
$access_token = 'pk.eyJ1IjoiNDEyZDQxMmRhMTIzIiwiYSI6ImNsdm1laHF3cDAxdGUybHFvcW82ajB6eHUifQ.NSwloMttXhtT1prPnzYaxQ'; MapBox access token
$url = "https://api.mapbox.com/geocoding/v5/mapbox.places/$zipcode.json?country=US&access_token=$access_token";
$response = file_get_contents($url);
$data = json_decode($response, true);
if ($data && isset($data['features'][0]['place_name'])) {
return $data['features'][0]['place_name'];
} else {
return "Location not found";
}
}
if (!$connect) {
die("Connect error: " . mysqli_connect_error());
}
$query = "SELECT * FROM `units`";
$result = mysqli_query($connect, $query);
$combinedArray = array();
if ($result) {
if (mysqli_num_rows($result) > 0) {
// Вывод данных каждой строки
while ($row = mysqli_fetch_assoc($result)) {
$location = getLocationDetails($row['location']);
$location_name = getLocationName($row['location']);
$combinedArray[] = array(
'available' => $row['available'],
'id' => $row['id'],
'name' => $row['name'],
'owner_id' => $row['owner_id'],
'location' => $location,
'dimensions' => $row['dimensions'],
'equipment' => $row['equipment'],
'capacity' => $row['capacity'],
'status' => $row['status'],
'location' => $row['location'],
'dimensions' => $row['dimensions'],
'location_name' => $location_name,
'coordinates' => $location,
'truck_type' => $row['truck_type'],
'home' => $row['home'],
'notes' => $row['notes'],
'datetime_available' => $row['datetime_available'],
'phone_number' =>$row['phone']
);
}
} else {
echo json_encode(array('error' => 'Data not found'));
exit;
}
} else {
echo json_encode(array('error' => 'Ошибка запроса: ' . mysqli_error($connect)));
exit;
}
mysqli_close($connect);
echo json_encode($combinedArray);
file_put_contents('../../JSON/db.json', json_encode($combinedArray, JSON_PRETTY_PRINT));
?>
PHP connect to DB:
<?php
$connect = mysqli_connect('localhost', 'root', '', 'software');
if (!$connect) {
die('Error connecting to database');
}
?>
Who knows what could be causing this and whether my code is correct or not ?
If you need any photos or video with how it work.
Please let me know.