I'm a newbie in Object-Oriented Programming so it would be nice if someone can help me ^^
i got this JS function rn:
function confirmDel(element) {
let confirmDel = confirm("u sure u want to delete?");
if (confirmDel) {
console.log(element);
window.location.href=="formprocess.php?firmadelete=";
alert(deleted");
}
else{
alert("deleting canceled");
}
}
and in my HTML i got
<a
class="btn btn-outline-danger"
href="formprocess.php?firmadelete=<?= $result['FirmenID']; ?>"
><i class="fa-solid fa-trash-can"></i></a>
</td>
Maybe u see my try. I want to ask "U sure u want to delete?" and if I'm pressing "yes" it should bring me to the href formprocess.php?firmadelete=<?= $result['FirmenID']; ?>
How I can translate the $result['FirmenID'] into the JS script?
Greetings from Germany ~Lampi
Assuming that the javascript is in a separate JS file and not just inline in the HTML itself (which would let you just add the same PHP you're using for adding it to the href), the easiest way to do this would probably be to just add a data attribute to the HTML element and then use JS to read the value from that.
If element passed in is the link that was clicked on, you could do something like this in the HTML:
<a class="btn btn-outline-danger" href="formprocess.php?firmadelete=<?= $result['FirmenID']; ?>" data-id="<?= $result['FirmenID']; ?>>
<i class="fa-solid fa-trash-can"></i>
</a>
and this in the JS:
function confirmDel(element) {
...
if (confirmDel) {
console.log(element);
const id = element.getAttribute('data-id');
window.location.href == "formprocess.php?firmadelete=" + id;
...
or something similar.
href a link always needs a href, so I changed it to '#' (which is the top of the page).
onclick I use click-event (onclick) to call the function confirmDel. The event.preventDefault(); function is called to cancel the href.
data-id The FirmId is saved in data-id. The possible special characters are escaped with the htmlspecialchars function, this is not neccecery if you are certain that FirmenID is always a number.
<a class="btn btn-outline-danger" href="#" onclick="confirmDel(this); event.preventDefault();" data-id="<?= htmlspecialchars($result['FirmenID'], ENT_HTML5 | ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8"); ?>"><i class="fa-solid fa-trash-can"></i> testme</a></td>
JavaScript The only thing that is changed in the JavaScript code is adding the FirmenID behind the URL. This is done by retrieving the id by accessing data-id (*.dataset.id).
Alert The Alert box will never be displayed, since the URL of the page changes. If you want the URL to be executed in the background instead, please check XMLHttpRequest or Fetch.
function confirmDel(element) {
let confirmDel = confirm("u sure u want to delete?");
if (confirmDel) {
console.log(element);
window.location.href="formprocess.php?firmadelete=" + element.dataset.id;
alert("deleted");
}
else{
alert("deleting canceled");
}
}