Refresh a message within a div or any tag after specific time period which will contain a value from database

Refresh a message within a div or any tag after specific time period which will contain a value from database

In ajax function, we are sending a request to a page which is having a database query to fetch the data from database. The ajax function is called within setTimeout function so that it will be called after specified time 

interval. And the data fetched by ajax page is shown in li tag here. You can use div also. And get_unread.php will have the database query to fetch the unread messages.

Write this code in header file to display on every page

<script>
function executeQuery() {
$.ajax({
url: 'ajax/get_unread.php',
success: function(data) {
// do something with the return value here if you like
//alert(data);
$("#unread").html(data);
}
});
setTimeout(executeQuery, 60000); // you could choose not to continue on failure...
}

$(document).ready(function() {
// run the first time; all subsequent calls will take care of themselves
executeQuery();
setTimeout(executeQuery, 60000);
});
</script>


Take this li(or div or any structure) on every page wherever you want to display the message

<li id="unread" class="active" style="float: right; margin-right: 2%; font-size: small;"></li>


get_unread.php

<?php include '../connection.php';
$result = mysql_query("SELECT * FROM tbl_mail WHERE `to` = '$_SESSION[username]'
      AND `read` = 0
      ORDER BY maildate DESC");
echo '<a href="internal_communication.php"> You have ' . mysql_num_rows($result) . ' unread messages</a>';
?>



Comments