I am trying to make a notification system for a school project, jQuery is not allowed! Each time there is a notification I’m creating a div with an onclick button to acknowledge the notification with the id as parameter.
Then my function JavaScript get the div and pass the notification to a 1 status in SQL with ajax and finally close the div. When I only have one notification it’s working perfectly but when there is multiple div, my script seem unable to close each notification and I need to refresh my page to close each div.
My code:
 foreach($notifs as $notif){
                            $id = $notif["id"]; ?> 
                             <div id="notifAlert">
                                <p><?= $notif["content"]; ?><br> <button onclick="seenNotif(<?= $id; ?>)">OK</button></p>
                            </div>
                    <?php  } } ?>
function seenNotif(idNotif){
    console.log(idNotif);
        const divNotif = document.getElementById("notifAlert");
        const footer = document.getElementById("foot");
            const req = new XMLHttpRequest();
            req.onreadystatechange = function () {
            if (req.readyState === 4){
                footer.removeChild(divNotif);
            }
        };
        req.open("GET", "notifStatut.php?idNotif="+idNotif);
        req.send();
        
}
require ("functions.php");
$idNotif = $_GET["idNotif"];
    $connection = connectDB();
    $query = $connection->prepare("UPDATE notifications SET statut = :statut WHERE id = :idNotif");
    $query->execute([
        "statut" => 1,
        "idNotif" => $idNotif
    ]);
Advertisement
Answer
As said, id’s have to be unique. The simplest solution is to change
in PHP
<div id="notifAlert"> to
<div id="notifAlert<?= $id ?>">
(add $id to the id to make it unique)
and in javascript
document.getElementById("notifAlert") to
document.getElementById("notifAlert"+idNotif)
Th should get you the div you want.