I'm a beginner in HTML5. Now I'm trying to display the number of rows in a table using HTML5 Server-Sent Events. I was able to get the number of rows and display it inside a div tag.
Javascript
<script>
var evtSource = new EventSource("messages.php");
console.log("Inside 1");
console.log(evtSource);
evtSource.onmessage = function(e) {
var no_of_messages=e.data;
if(no_of_messages > 0)
{
$("#Messages").html(e.data);
}
else
{
$("#Messages").html(e.data);
}
I used a PHP script to get the rows from the table.
PHP
<?php
date_default_timezone_set("America/New_York");
header("Content-Type: text/event-stream\n\n");
$counter = rand(1, 10);
while (1) {
// Every second, sent a "ping" event.
echo "event: ping\n";
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT count(*) FROM messages';
mysql_select_db('apartment');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_assoc($retval))
{
$message_count=$row['count(*)'];
}
mysql_close($conn);
echo 'data: {"Messages": "' . $message_count . '"}';
echo "\n\n";
// Send a simple message at random intervals.
$counter--;
if (!$counter) {
echo 'data:' . $message_count . "\n\n";
error_log($message_count);
$counter = rand(1, 10);
}
ob_flush();
flush();
sleep(1);
}?>
Now, I want to display it as a notifications in the HTML page so that the user can see it as it pops up.
What I have done -
<div style="height: 70px; width:100%;border-style: solid;
border-bottom-width:1px;border-color: #ccc" id="dashboard">
<div id="Messages"><button id="button" type="button">Number of Messages</button></div>
</div>
With the above HTML I can display the Number of Messages, but I want to -
1. Change the color of the button when number of messages is above 0 and the color of the button should change to Green from initial color Red.
2. Is it possible to create a balloon like notification with this.
To change the color you can use
if (no_of_messages > 0){
document.getElementById("button").style.background-color="red";
} else {
document.getElementById("button").style.background-color="green";
}
But I am not too sure what is meant by 'balloon like', I will update my answer if you might explain a little bit more.
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.