I'm writing a PHP script that echoes a number which represents the amount of unread messages.
I have the following code which processes the PHP every 30 seconds.
setInterval(function (){
$.ajax({
url: "php/notifications_counter.php",
cache: false,
success: function(number){
$("#notification_counter").show();
$("#notification_counter_number").text(number);
}
});
},5010);
The number that the PHP echoes should be inserted into the div called '#notification_counter_number'. And indeed the number gets inserted. But for some strange reason, together with the number also the commenting inside the php file gets echoed? I can't get this to work properly.
Additionally, I want the #notification_counter to show when there is a number echoed, but hidden when there is none. So i tried the following code for that:
...success: function(number){
if (number > 0) {
$("#notification_counter").show();
$("#notification_counter_number").text(number);}
else {$("#notification_counter").show();}
}
This doesn't work either:( The div always gets hidden, even if PHP outputs a number more than 0. Hope you guys can help.
UPDATE: this is my php file:
<!--
blabla commenting, so this gets visible as text in DIV as well. Strange...
!-->
<?php
include "config.php";
//Count unread messages from database
$Number_Query = mysqli_query ($mysqli, "SELECT * FROM notifications WHERE Notification_Read='0' ");
$Notification_Count = mysqli_num_rows($Number_Query);
if ($Notification_Count > 0) {
echo "$Notification_Count"; }
//Close connection
mysqli_close($mysqli);
?>
<!-- -->
is an HTML comment, that is output to the browser, simply change to php comments:
<?php
/*
blabla commenting, so this gets visible as text in DIV as well. Strange...
*/
include "config.php";
Whilst you are making changes, it would also make sense to output JSON, which would allow you to add extra data if needed (eg comment times, author etc):
$Notification_Count = mysqli_num_rows($Number_Query);
header('Content-Type: application/json');
echo json_encode(array('count'=>$Notification_Count));
//javascript
success: function(data){
if (data.count > 0)...
So when you get a page via ajax its going to return the entire body, not just what you can see in a browser. so the <!--
html comment is being returned in the string. You need to remove that output altogether by using php comments or your calculation of number > 0
will fail.
If you absolutely can't change the PHP output for whatever reason you can strip the response of all characters by doing something like:
if (number.replace(/\D/g,'') > 0) {
but that's pretty gross. better to clean up your php file.