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);
});
Related
What i want to do is, to show a message based on certain condition.
So, i will read the database after a given time continuously, and accordingly, show the message to the user.
But i want the message, to be updated only on a part of the page(lets say a DIV).
Any help would be appreciated !
Thanks !
This is possible using setInterval() and jQuery.load()
The below example will refresh a div with ID result with the content of another file every 5 seconds:
setInterval(function(){
$('#result').load('test.html');
}, 5000);
You need a ajax solution if you want to load data from your database and show it on your currently loaded page without page loading.
<script type="text/javascript" language="javascript" src=" JQUERY LIBRARY FILE PATH"></script>
<script type="text/javascript" language="javascript">
var init;
$(document).ready(function(){
init = window.setInterval('call()',5000);// 5000 is milisecond
});
function call(){
$.ajax({
url:'your server file name',
type:'post',
dataType:'html',
success:function(msg){
$('div#xyz').html(msg);// #xyz id of your div in which you want place result
},
error:function(){
alert('Error in loading...');
}
});
}
</script>
You can use setInterval if you want to make the request for content periodically and update the contents of your DIV with the AJAX response e.g.
setInterval(makeRequestAndPopulateDiv, "5000"); // 5 seconds
The setInterval() method will continue calling the function until clearInterval() is called.
If you are using a JS library you can update the DIV very easily e.g. in Prototype you can use replace on your div e.g.
$('yourDiv').replace('your new content');
I'm not suggesting that my method is the best, but what I generally do to deal with dynamic stuff that needs access to the database is the following method :
1- A server-side script that gets a message according to a given context, let's call it "contextmsg.php".
<?php
$ctx = intval($_POST["ctx"]);
$msg = getMessageFromDatabase($ctx); // get the message according to $ctx number
echo $msg;
?>
2- in your client-side page, with jquery :
var DIV_ID = "div-message";
var INTERVAL_IN_SECONDS = 5;
setInterval(function() {
updateMessage(currentContext)
}, INTERVAL_IN_SECONDS*1000);
function updateMessage(ctx) {
_e(DIV_ID).innerHTML = getMessage(ctx);
}
function getMessage(ctx) {
var msg = null;
$.ajax({
type: "post",
url: "contextmsg.php",
data: {
"ctx": ctx
},
success: function(data) {
msg = data.responseText;
},
dataType: "json"
});
return msg;
}
function _e(id) {
return document.getElementById(id);
}
Hope this helps :)
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. :)
I have a simple installer that's divided in segments, not by syntax, but just by logic. Here's how it works:
if ($_POST['install'] == "Install")
{
// fetches user values
// creates tables
// creates some files
// creates some emails
// inserts relevant stuff into the database
// finishes
}
The code is too long and unnecessary for this question. Each of those steps counts as 20% complete for the installation, how would I make a progress bar displaying the info to the user? I'd like this for two reasons, one is for them to keep track, other is for them to know they shouldn't close the browser tab before it's done.
Now my idea is to assign a variable to each part of the code, for instance $done = 20% in the first, $done = 40% in the second etc, and simply show progress bar based on that variable. The the only thing I don't know is how to show the progress bar?
Thanks
My recommended solution:
Create separate ajax requests for each step in your process like so...
// do first step
$.ajax({
url: myUrl + '?step=1',
success: function() {
// update progress bar 20%
}
});
// do second step
$.ajax({
url: myUrl + '?step=2',
success: function() {
// update progress bar 40%
}
});
// etc.
If you want to be DRY, try this:
var steps = 5;
for (var i = 1; i <= steps; i++) {
$.ajax({
url: myUrl + '?step=' + i;
success: function() {
// update success incrementally
}
});
}
With jQuery UI progressbar:
$(function() {
$("#progressbar").progressbar({
value: 0
});
var steps = 5;
for (var i = 1; i <= steps; i++) {
$.ajax({
url: myUrl + '?step=' + i;
success: function() {
// update success incrementally
$("#progressbar").progressbar('value', i * 20);
}
});
}
});
Ref. http://jqueryui.com/progressbar/#default
The best practice is to store the progress value in a db or a key-value storage system such as APC, Memcache or Redis. And then retrieve the progress with an ajax query.
A good jquery plugin is progressbar bar from jQuery-ui, and you can use json to encode the progress value:
// GET /ajax/get-status.json
{
"progress":10,
"error":"",
"warning":""
}
The page:
<div id="error" style="color: red"></div>
<div id="warning" style="color: yellow"></div>
<div id="message"></div>
<div id="progressbar"></div>
<script type="text/javascript">
jQuery(document).ready(function() {
$("#progressbar").progressbar({ value: 0 });
$.ajaxSetup({ cache: false });
function updateProgress() {
jQuery.getJSON("/ajax/get-status.json", function(response) {
if (response.error) {
$("#error").html( response.error );
return;
} else {
$("#progressbar").progressbar( 'value', parseInt( response.progress ) ); // Add the new value to the progress bar
$("#message").html( response.message );
$("#warning").html( response.warning );
if(parseInt( response.progress ) < 100){
setTimeout(updateProgress, 1);
}
}
});
}
updateProgress();
});
</script>
You can use an HTML5 progress bar.
Send ajax request and return the percent complete.
Change the progress tag's value.
<progress id='p' max="100" value="50"></progress>
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 */);
I've looked around a bit and haven't found an answer to this yet.
I have an ajax request that when you click the button it sends info to the server and hides the current div and loads a loading gif. I have it set so when the server responds it gets rid of loading gif and shows the content from the server.
code:
$("#submit").click(function(e){
e.preventDefault();
var $domain = $.fn.HTTP($('#domain').val());
if(!$.fn.ValidURL($domain)){
$('#domainerror').fadeIn(500);
return false;
}
if($('#domainerror').css('display')!=='none'){
$('#domainerror').fadeOut(350);
}
$('#question').hide(500, function(){
$('#waiting').show(350);
});
$.getJSON('http://localhost/file.php',
{
i: $domain
},
function(data){
$('#answer').html(data.message + $('#trybutton').html());
$('#waiting').hide(350, function(){
$('#answer').show(350);
});
});
});
The problem is jQuery receives the response from the server too fast and the loading gif doesn't disappear.
However if I tell the server to sleep for 3 seconds it works just fine. This is not the solution I want.
Any ideas?
Surely it's a good thing your users aren't having to see a loading animation because it's so fast?!
Anyway, the problem is that the animation is taking at least 500ms - animations are processed asynchronously, at the same time as your AJAX request. Instead of making the server sleep, which is arguably a waste of CPU, make the browser wait instead, before you send the AJAX request.
Put the call in a setTimeout() function, this example will make it wait 3 seconds:
setTimeout(function() {
$.getJSON('http://localhost/file.php',
{
i: $domain
},
function(data){
$('#answer').html(data.message + $('#trybutton').html());
$('#waiting').hide(350, function(){
$('#answer').show(350);
});
});
}, 3000);
The ideal solution however would be to not use animation effects and just use show() and hide().
Get rid of the delay in showing the waiting animation, so it's not still showing up when the request returned.
$('#question').hide() //was 500
$('#waiting').show(); //was 350
If you add all up that's almost a second later. By that time the ajax request may have returned in most systems, so it's not worth to be still animating by that point
Use Javascript's setTimeout. Code may look something (perhaps not exactly) like this:
setTimeout("getResponse()", 3000);
function getResponse() {
$.getJSON('http://localhost/file.php',
{
i: $domain
},
function(data){
$('#answer').html(data.message + $('#trybutton').html());
$('#waiting').hide(350, function(){
$('#answer').show(350);
});
});
}
That way you've got your AJAX request still sending your i variable to the server, processing the code in file.php and sending back data which you can handle. The only trick is to put this in a function (not required, but it certainly makes the setTimeout function look prettier) and call it after 3000 milliseconds.
Seems like the ajax callback is executed before the question hiding ends, and the $('#waiting').show(350); comes after $('#waiting').hide(350, ...). You have three possibilities to solve that:
If you'd show the #waiting img immidiately (not waiting for the question to fade out), this won't happen; the answer should then also not wait for #waiting to hide.
Or you use a variable to indicate that the answer is already fading in when the question has faded out, and show no animation then:
var answered = false,
waiting = false;
$('#question').hide(500, function(){
if (!answered) {
waiting = true;
$('#waiting').show(350);
}
});
$.getJSON('http://localhost/file.php', {
i: $domain
}, function(data){
$('#answer').html(data.message + $('#trybutton').html());
answered = true;
if (waiting) {
$('#waiting').stop().hide(350, function(){
$('#answer').show(350);
});
} else {
$('#answer').show(350);
}
});
If you want the four animations to show always and consecutively (at least 1550ms), you'd need to code them manually:
var showanswer = false;
$('#question').hide(500, function() {
$('#waiting').show(350, function() {
if (showanswer) // already loaded
showanswer(); // execute callback
else
showanswer = true; // mark as shown
});
});
$.getJSON('http://localhost/file.php', {
i: $domain
}, function(data){
$('#answer').html(data.message + $('#trybutton').html());
function animate() {
$('#waiting').hide(350, function(){
$('#answer').show(350);
});
}
if (showanswer) // waiting image shown
animate();
else
showanswer = animate; // set as callback
});