Fetch number of rows using javascript

I’m trying to fetch number of rows that were not in another table and show them using javascript.

First, in the main page, it will list the inbox name from inboxtb table. Then I have a script that should pass the value (inboxid) to another file and return the number of result back to the main file.

I’ll fetch first all the inbox row (main page):

while($stmt->fetch()){
  echo '<li><a href="#" data-artid="'.$inboxid.'" id="loadmessage">'.$name.'</a> <span id="loadnumber"></span></li>';
}

Then my script:

$(function(){
  $('.loadmessage').ready(function(){
    var elem = $(this);
    var dataString = "inboxid="+elem.attr('data-artid'); /* STORE THE INBOXID */
    $.ajax({
      type: "GET",
      url: "../fetch/noofres.php", /* THIS IS WHERE THE NUMBER OF UNREAD MESSAGES SHOULD COME FROM */
      data: dataString,
      success: function(data) {
        setInterval(function() { /* EVERY SECOND, THE NUMBER SHOULD REFRESH TO SEE CHANGES IN THE DATABASE */
          $('#loadunreadmessages').html(data); /* LOAD THE NUMBER TO THIS SPAN WITH THE ID OF loadunreadmessages */
        }, 1000);
      }
    });
    return false;
  });
});

And my noofres.php:

if($stmt = $con->prepare("SELECT a.messageid FROM messagetb a LEFT JOIN readtb b ON a.messageid = b.messageid WHERE a.inboxid = ? AND b.readid IS NULL")){
  $stmt->bind_param("i",$_GET["inboxid"]);
  $stmt->execute();
  $stmt->store_result();
  $noofunreadmessages = $stmt->num_rows;
  $stmt->close();
} /* END OF SECOND PREPARED STATEMENT */

if($noofunreadmessages != 0){
  echo '<span class="badges">'.$noofunreadmessages.'</span>';
}

But it doesn’t return a number, where it should. What am I doing wrong? Or a better script to do it?


Source: ajax

Leave a Reply