Javascript/PHP/AJAX notification problem

Greetings all. 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 :slight_smile:

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. If you need the external php file do not hesitate to ask. 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();

You might want to just show the PHP file and talk about how you are querying it for the various rows.

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; 
          }

This loop is doing nothing…

How do you pull each ‘total’ out of the array and assign it to ‘item’ ?

Never mind. I figured it out. Thanks

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.