i want real time update in $.post without reload or refresh - php

this is my PHP code_
if(isset($_REQUEST['show']))
{
$con=mysqli_connect("localhost","root","","server_name");
$show = mysqli_query($con, "SELECT * FROM name1 ORDER BY date DESC");
$html='';
while($showE = mysqli_fetch_array($show))
{
$html.= '<h3>'.$showE['un_name'].'</h3>';
$html.= '<div>'.$showE['un_name_dec'].'</div>';
}
echo $html;
//End of while loop
}
this is jquery code_
$.post('preprocessor.php', '&show=', function(data) {
$("#accordion").html(data);
$("#accordion").accordion({
collapsible: true,
icons: {
activeHeader: "ui-icon-triangle-1-s",
header: "ui-icon-triangle-1-e"
}
});
});
this is body_
<div id='accordion'>
</div>
i am not getting real time updates, everything is working, but the Ajax thing is not working... it works if i refresh or reload the page but not itself

What you are looking for is setTimeout.
$("#accordion").accordion({
collapsible: true,
icons: {
activeHeader: "ui-icon-triangle-1-s",
header: "ui-icon-triangle-1-e"
}
});
setInterval(makePostCall, 15000); // decide interval to fetch new updates. 15 sec for example
function makePostCall(){
$.post('preprocessor.php', '&show=', function(data) {
$("#accordion").html(data);
});
}
But this is not the proper way of doing this kind of stuff. Consider using Ajax Push Engine

it works if i refresh or reload the page but not itself
For this you need to use setInterval(); function which will check every specific time period which is given:
setInterval(function(){
$.post('preprocessor.php', '&show=', function(data) {
$("#accordion").html(data);
$("#accordion").accordion({
collapsible: true,
icons: {
activeHeader: "ui-icon-triangle-1-s",
header: "ui-icon-triangle-1-e"
}
});
});
},5000); //<---- runs every 5000 ms
This will run every 5 seconds and will update the #accordion div.

try:
$.post('preprocessor.php', {show:''}, function(data) {
$("#accordion").html(data);
$("#accordion").accordion({
collapsible: true,
icons: {
activeHeader: "ui-icon-triangle-1-s",
header: "ui-icon-triangle-1-e"
}
});
},'html');

Are you setting interval to call the code in certain intervals? All you need to do is,
on JavaScript add:
setinterval(function(){/* do the post here */ },1000 /*this is time */);

Related

JQuery wallboard with sound notifications and flashing div/table cells

I have a page with SQL Queries on inside a table which show results on a large screen.
I then browse to index.php which contains this code:
// <![CDATA[
$(document).ready(function() {
// This part addresses an IE bug. without it, IE will only load the first number and will never refresh
$.ajaxSetup({ cache: false });
setInterval(function() {
$('.container').load('data.php');
}, 2000); // the "2000" here refers to the time to refresh the div. it is in milliseconds.
});
// ]]>
HTML :
<div class="container"><h3>Loading Data...</h3></div>
So it loads this page constantly.
What i would like to do is have it so if any of the queries contain data that needs to have action taken on it, the table cell will flash 2 colours and also a sound will play every 5 minutes.
What would be the best way to do this and keep the constant page load?
I would change the .load() into an ajax call, which calls a function when done. Check the script below:
// Prepare the audio - replace the link with your own mp3
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'http://www.uscis.gov/files/nativedocuments/Track%2090.mp3');
// Global that will control the flashing / playing of sound
var alertUser = false;
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // Fix IE bug
setInterval(function(){
$.ajax({
url: "data.php",
complete: function( jq, content ){
$('.container').html( jq.response );
if( jq.response.indexOf( 'from' ) != -1 ) { // your logic goes here to decide the warning
alertUser = true;
} else {
alertUser = false;
}
}
});
}, 2000);
setInterval(function(){
if( alertUser ) {
// play tune
audioElement.play();
// flash background
window.setTimeout( function(){
$('.container').css('background-color','red')
}, 200 );
window.setTimeout( function(){
$('.container').css('background-color','blue')
}, 400 );
window.setTimeout( function(){
$('.container').css('background-color','transparent')
}, 600 );
}
}, 1000);
});

Update div after jquery ajax request only if content is new

I've recently started learning jQuery and I'm trying to make a little messaging system, I've gotten the messages to update every 2 seconds. However, I don't want the messages to update if there aren't any new messages. This is my current message updating code.
$(document).ready(function () {
setInterval(function() {
$.get("get_messages.php", function (result) {
if ($('.messages').html() != result){
$('.messages').html(result);
}
});
}, 2000);
});
The if statement doesn't seem to be working even though the div and result should be the same.
I hope that you have timestamp or messageID on server that could tell your script if there are new messages after last check.
ex.
var lastMessageID = 0;
function checkMessages(){
$.ajax(url,{
data:{
last_message_id:lastMessageID
},
success:function(data){
// Count new messages
if (Object.keys(data).length > 0){
$.each(data,function(index, item){
$('.messages').prepend("<span class='message'>"+item.message+"</span>");
});
// We suggest that this is our last message
lastMessageId = data[Object.keys(data).length-1].id;
}
}
});
}
var intervalM = setInterval(function(){
checkMessages();
},2000);
And please save some trees by using gziped JSON data. :)

jquery Send Heartbeat when Viewing Page

I've written the following Jquery to send a Heartbeat back to PHP every 3 seconds and it works fine. The reason I'm doing this is to understand what users are currently logged in and using the site.
setInterval(function () {
$.post('includes/heartbeat.php', {'heartBeatConfirmation': '1'});
},3000);
The catch I'm finding is it continues to heartbeat when users aren't looking at the site - eg: they still have the browser open but are looking at other pages or doing something else.
Is there a way to update this so it only sends the AJAX heartbeat if the user is using the site?
You can check if window is focused and only heartbeat if it's focused.
Try this:
$(window).focus(function() {
heartbeat = setInterval(function () {
$.post('includes/heartbeat.php', {'heartBeatConfirmation': '1'});
},3000);
})
.blur(function() {
clearInterval(heartbeat);
});
$(window).focus();
$(document).ready(function(){
heartBeatInterval = null;
$(window).focus(function() {
if(heartBeatInterval == null){
heartBeatInterval = setInterval(function () {
$.post('includes/heartbeat.php',
{'heartBeatConfirmation': '1'}
);
console.log('We have the fouces of the active tab');
},1000);
}
});
$(window).blur(function() {
heartBeatInterval = null;
console.log('We have the lost the focus of the active tab');
});
});
It is just a matter of taste I guess:
$(window)
.on('mouseleave', function(){
clearInterval(inside);
})
.on('mouseenter', function(){
inside = setInterval(function () {
$.post('includes/heartbeat.php', {'heartBeatConfirmation': '1'})
}, 3000)
})
JSFIDDLE ( Reminder: window is "Result" Frame ).

Get/fetch data from database without refresh the page

Hi I'd like some help please. I'm currently learning Ajax and Json so I don't have much experience on it.
I have followed this tutorial in order to fetch the data without page refresh, but I'm having some concerns on it.
The script works fine, the only problem I found is that if I hit refresh it takes a lot of time (about 5-10 seconds)to load the content again.
In Firebug I can see in the Console that it is continiously binding as it's sending requests all time.
Here's the code
HTML
<div class="ajax_results">
<ul id="results"></ul>
</div>
PHP script
$query = "SELECT `img_id`, `image_name`, `title` FROM `images` ORDER BY `img_id` DESC LIMIT 5 ";
$run = mysqli_query($connection, $query) or die(mysqli_error($connection));
$json = array();
while ($row = mysqli_fetch_array($run, MYSQLI_ASSOC)) {
array_push($json, array('image_name' => $row['image_name'],
'title' => $row['title']));
}
echo json_encode(array("json" => $json));
and the JS
$(document).ready(function() {
refresh();
});
function refresh() {
setTimeout(function() {
update_content();
refresh();
}, 200);
}
function update_content() {
$.getJSON("fetch_data.php", function(data) {
$("ul#results").empty();
$.each(data.json, function() {
$("ul#results").append("<li><img src=\"img/uploads/"+this['image_name']+"\" /><br />"+this['title']+"</li>");
});
});
}
Is this a problem?? Can I improve somehow the code?? Any help would be appreciated
To give some extra feedback. If the $.getJSON is directly placed in $(document).ready(function() the content loads more quickly, but if any updates occured eg in the title won't show without refreshing the page. What I actually want to achieve is load the content and if any changes happened to show them without refreshing the page.
Here's another approach to the issue
$(function() {
update_content();
});
function update_content() {
$.getJSON("fetch_data.php", function(data) {
$("ul#results").empty();
$.each(data.json, function() {
$("ul#results").append("<li><img src=\"img/uploads/"+this['image_name']+"\" /><br />"+this['title']+"</li>");
});
setTimeout(function(){
update_content();
}, 1000);
});
}
Here I've moved the setTimeout call into the update_content() function, and increased the timeout to give the browser a bit more breathing room, personally I wouldn't call this every second but it's just an example, I'd probably go with 10 seconds or even longer.
If you don't want it to fire off repeatedly remove the entire setTimeout block.
$(function() {
update_content();
});
function update_content() {
$.getJSON("fetch_data.php", function(data) {
$("ul#results").empty();
$.each(data.json, function() {
$("ul#results").append("<li><img src=\"img/uploads/"+this['image_name']+"\" /><br />"+this['title']+"</li>");
});
});
}

Show a div when a variable is set and let it disappear after x seconds

I have a php page with a variable that is set true or false on pageload. I want to show a specific div when the variable is true and then the div disappears after x seconds. When its false the div stays hidden.
My code shows the div but it doesn't disappear after x seconds.
if($showNotification == TRUE){
echo "<div class='notification'>notification!!</div>";
echo '<script type="text/javascript">
$(document).load(
function() {
$("div.notification").fadeIn();
setTimeout(function() {
$("div.notification").fadeOut("slow");
}, 3000);
});
</script>';
}
Replace your JS with this:
$(function() {
$('div.notification').hide().fadeIn().delay(3000).fadeOut('slow');
});
Demo: http://jsfiddle.net/nEsg9/
Instead of using:
$(document).load( ...
use
$(document).ready( ...
if($showNotification == TRUE){
echo "<div class='notification' style='display:none'>notification!!</div>";
echo '<script type="text/javascript">
$(document).load(
function() {
$("div.notification").fadeIn();
setTimeout(function() {
$("div.notification").fadeOut("slow");
}, 3000);
});
</script>';
}
It shows because it is not hidden before you do the fadein. So fadein has no effect (it is already there).
Use ready instead of load.
Here is a working example, but without fade in, cause it's always displayed
http://jsfiddle.net/2JKxr/1/
$(document).ready(
function() {
$("div.notification").fadeIn();
setTimeout(function() {
$("div.notification").fadeOut("slow");
}, 3000);
});

Categories