简体   繁体   中英

javascript notification checker script Uncaught Reference Error

I have this notification checker and i don't know whats wrong with this js code, i have errors on checkMessage() : Uncaught Reference Error: checkMessage is not defined

the js code:

function checkMessage(){

if (window.XMLHttpRequest) 
  {
  xmlhttp=new XMLHttpRequest();
  }
else
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

xmlhttp.onreadystatechange=function() //when the request is submitted...
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200 //...and everything is ok...
    {
        if(xmlhttp.responseText>0){ // if the response text is greater than 0

            document.title="("+xmlhttp.responseText+")"+"My Social Network - Welcome"; 

            document.getElementById('checkMsg').innerHTML="<b>" + xmlhttp.responseText+" Notifications</b>";
        }
        else 
            document.title="My Social Network - Welcome";

            document.getElementById('checkMsg').innerHTML="No notifications";
    }
  }

xmlhttp.open("GET","checkMessage.php?user_id="+"1",true); 
xmlhttp.send();
}

the checkmessage.php code:

<?php
        include 'dbm.php'; //database settings from an external file

        $user = $_SESSION['user'];

        $get_count_messages = mysql_query("SELECT message FROM notifications ");
        $row = mysql_num_rows($get_count_messages); // count how many rows the query returned

        echo "$row"; //return the value
?>

The html code:

<html>
    <head>

        <script type="text/javascript" src="notifications.js"></script>
        <script type="text/javascript">
            setInterval("checkMessage()", 1000);
        </script>
    </head>
    <body>
        <div id="checkMsg"></div>
    </body>
</html>

I think your setInterval function should look like:

setInterval(checkMessage, 1000);

Because setInterval expect a function as parameter.

It's just a simple example to make a difference betwen the number of notifications

 if (xmlhttp.readyState==4 && xmlhttp.status==200 //...and everything is ok...
 {    
     var title = "";
     var message;
     if(xmlhttp.responseText > 0)
     {
        title += "(" + xmlhttp.responseText + ")";
        if(xmlhttp.responseText > 1)
           message = "<b>" + xmlhttp.responseText + " Notifications</b>";
        else
           message = "<b>" + xmlhttp.responseText + " Notification</b>";
     }
     else
         message = "No notifications";

     title += "My Social Network - Welcome";

     document.title = title; 
     document.getElementById('checkMsg').innerHTML= message;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM