Я использую асинхронный php для получения и установки данных в моей базе данных. Я отображаю результат в виде таблицы html. Проблема в том, что я пытаюсь добавить действия в эту таблицу, используя javascript (когда пользователь нажимает значок удаления, строка удаляется в php). К сожалению, js запускается до загрузки html. Я пробовал назначать после загрузки, но onclick запускается каждый раз снова и снова. Я добавил все соответствующие файлы.
Вот ссылка на папку проекта
Скажите, пожалуйста, нужно ли мне добавить что-нибудь еще. Я использую xampp для своего локального сервера.
<?php
include './dbCred.php';
$id = $_POST["product-id"];
$name = $_POST["product-name"];
$price = $_POST["product-price"];
$description = $_POST["product-description"];
// echo $id."<br>";
// echo $description;
$conn = mysqli_connect($servername, $username, $password,);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_select_db($conn, "assignment5")) {
mysqli_close($conn);
} else {
$query = "CREATE DATABASE assignment5";
mysqli_query($conn, $query);
// if (mysqli_query($conn, $query)) {
// // echo "Database created succesfully<br />";
// } else {
// // echo "Error creating database: " . mysqli_error($conn);
// }
mysqli_close($conn);
}
$conn = mysqli_connect($servername, $username, $password, $dbname);
$query = "create table product(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
prod_id VARCHAR(30) NOT NULL,
prod_name VARCHAR(100) NOT NULL,
prod_price VARCHAR(100) NOT NULL,
prod_desc VARCHAR(200)
)";
$conn->query($query);
// if (mysqli_query($conn, $query)) {
// // echo "Table created succesfully<br>";
// } else {
// // echo "Table already exists ". $conn->error;
// }
$query = "insert into product (prod_id, prod_name, prod_price, prod_desc)
VALUES('$id', '$name', '$price', '$description')";
$conn->query($query);
$result = $conn->query("select * from product order by id desc limit 5");
echo "<table>";
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>";
$id = $row["prod_id"];
$name = $row["prod_name"];
$price = $row["prod_price"];
$description = $row["prod_desc"];
$description = strlen($description) > 20 ? substr($description, 0, 20)."..." : $description;
echo "<td>".$id."</td><td>".$name."</td><td>".$price."</td><td>".$description."</td>";
echo "</tr>";
}
}
echo "</table>";
mysqli_close($conn);
?>
window.onload = function () {
document.getElementById('new-product-form').onsubmit = function (e) {
e.preventDefault();
}
document.getElementById("range-form").onsubmit = function (e) {
e.preventDefault();
}
};
function clearOutput() {
document.getElementById("primeOutput").innerHTML = "Prime numbers will appear here...";
}
function findPrimary() {
var inputs = document.getElementById("range-form").getElementsByTagName("input");
var num1 = inputs[0].value;
var num2 = inputs[1].value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
document.getElementById("primeOutput").innerHTML = this.responseText;
}
}
xmlhttp.open("POST", "./findPrime.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("num1=" + num1 + "&num2=" + num2);
}
getProducts();
function getProducts() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("tableBody").innerHTML = this.responseText;
assign();
}
}
xmlhttp.open("POST", "./getProduct.php", true);
xmlhttp.send();
}
function addProduct() {
var inputs = document.getElementById("new-product-form").getElementsByClassName("form-control");
var id = inputs[0].value;
var name = inputs[1].value;
var price = inputs[2].value;
var description = inputs[3].value;
if (name.length == 0 || id.length == 0 || price.length == 0) {
document.getElementById("new-product-form").classList.add("was-validated");
return;
}
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("tableBody").innerHTML = this.responseText;
assign();
for (var i = 0; i < 4; i++) {
document.getElementById("new-product-form").getElementsByClassName("form-control")[i].value = "";
}
}
}
xmlhttp.open("POST", "./addProduct.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("product-id=" + id + "&product-name=" + name + "&product-price=" + price + "&product-description=" + description);
}
var deleteList = document.getElementById("tableBody").getElementsByClassName("fa-trash-o");
console.log(deleteList.innerHTML);
function assign() {
for (var i = 0; i < deleteList.length; i++) {
var deleteIcon = deleteList[i];
var pid = deleteIcon.parentNode.id;
console.log("herlkje");
console.log(pid);
}
}
deleteList[0].onsubmit = function deleteProduct() {
console.log("kd");
}
:root {
--primary-red: rgb(254,74,86);
--background-white: rgb(236,232,225);
--primary-blue: rgb(15,25,35);
}
.navbar img {
width: 40px;
}
.navbar .navbar-brand .red {
color: var(--primary-red);
}