Message count notification problem

Greetings. I would like to know if anyone here is fluent enough with javascript to be able to assist me in correcting a notification problem. I am attempting to use javascript to access an external php file to select a message count from various users in a database on intervals. I am able to get it to work if there is ONLY one user. However it does not work for more than one. My print_r() on the external php file does show all messages but the javascript apparently is the failure. I have tried to use:

var elem = document.querySelectorAll(’.counter’);
var elem_array = Array.prototype.slice.call(elem);

However, this did not show any data as it stated “undefined”.

My current javascript code is below which does work for only the first row of data from the database. Thank you in advance.

       function call_notification(elem) {        
        setInterval(function() {            
           var xml = new XMLHttpRequest();            
            xml.onreadystatechange = function() {
            if(this.readyState == 4 || this.status == 200) {
                const elem = document.querySelector('.counter');                   
                elem.textContent = this.responseText;   
                console.log(elem.textContent);                    
               }
          };
        
        xml.open("POST", "test.php", true);
        xml.send();             

           }, 5000);        
      }    
        
      call_notification();




Here is the external PHP file if anyone needs to see it.




        $me = $_SESSION['userid'];
        $sql = $database_connection->prepare("SELECT COUNT(`id`) AS `total` FROM `messages` WHERE `receiver` = :me");
         $sql->bindParam(':me', $me);    
         $sql->execute(array(
            ':me' => $me       
          )); 
          $result = $sql->fetchAll();
         //This print shows everything as it should
         //print_r($result);

        foreach($result as $item) { 
              $item['total'];   
        }  

      $total_new = $item['total']; 

        if($total_new > 0) {        
             echo $total_new; 
          }

That query should only ever return a single row, as long as the userID is in the session.

Thanks, I am looking to return all messages from each user who is NOT the current $_SESSION(‘userid’) to the current $_SESSION(‘userid’) who happens to be the receiver. Do you know what needs to be done to correct this?

All messages or a count of all the messages?

Thanks, I needed a count of all the pertinent unread messages. I was however able to figure it out, thanks. I am just working on refreshing the count now.

Sponsor our Newsletter | Privacy Policy | Terms of Service