Live updating ajax charts - php

I have a website which serves around 20 - 50 widgets per second and I wanted to create a chart that automatically gets data from the server and then updates the chart and I want the chart to run from right to left as more data is added and remove the old values and add the new values. I would like a javascript and php solution.
I have tried google and cannot find any solutions for this and I found a tutorial once but now I have lost that link :( So any kind of help in form of a link, piece of code or what to look for will help.
One thing that I wanted was having the widget start with a delay of fetch data but start displaying the data after 5 seconds of the intial fetch and then fetch data every 2 seconds, however load data second by second. This would ease the load on the server while also generating smooth graphs.
Any help would be appreciated....
Something Like this for php
http://support.nevron.com/KB/a175/implement-real-time-chart-in-aspnet-application-using-ajax.aspx

So you just need two functions running at different intervals that have access to the same variable where all the data will be stored
function runChart() {
var dataObject = [];
fetchFromServer = function() {
//Make your Ajax call here
//and then update 'dataObject'
}
//set fetchFromServer to fire every 5 seconds
setInterval( function () { fetchFromServer() }, 5000 );
loadToChart = function() {
//In here keep track of what was the last data you added to the chart
//pull data-points from 'dataObject'
//and display the next data-point on the graph
}
//set loadToChart to fire every second
setInterval( function () { loadToChart() } ,1000);
}

Related

show notification with php when a specific data is changed in a database

I want to notify a person a count of the jobs available in a table in my database. In a table I have a list of 8 jobs and they have their avilability. I've done the count with a PHP query with SELECT COUNT(*) AS jobs... and created this ajax script which shows the count with an interval.
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#divToRefresh').load('notification.php'); //this contains the query
}, 30000);
});
However, I am not sure how I can make it so when the user sees the notifcation alert, they will close it and it doesn't appear again until there's a new available job.
I can't find anything on the good ol google either.
Your jQuery function is running in 30 seconds intervals polling data from server. notification.php returns pre-rendered HTML containing (I assume among other things) the number of jobs available.
Check the number of available jobs and show notification based on that:
setInterval(function() {
var oldNumberOfJobs = newNumberOfJobs = 0;
$('#divToRefresh').load('notification.php'); //this contains the query
newNumberOfJobs = $('#divWithJobsCount').text;
if (newNumberOfJobs > oldNumberOfJobs) {
// show notification to the user
}
oldNumberOfJobs = newNumberOfJobs;
}, 30000);
To be more specific (showing/hiding notifications), I need to see your HTML.
This solution feels bulky. The whole pre-rendered HTML is being reloaded again and again. A nicer approach would be to only return the number of jobs available and only update that number using jQuery.
Also, it might be a good idea to return the latest job_id as well as the total number of jobs available. This way, you could check if the latest job_id that is already stored in the front end matches the newly received job_id. And only if they don't match you would update the counter and show new notification.
update
Here is a jsfiddle.js which covers your case. Jobs counter is simulated with current number of minutes. The function checks every 15 seconds if the number of minutes has changed. Once it happens, an alert notification is shown (but only if the old one was closed).
setInterval in jsfiddle is written using a mock object so that it is testable in the browser without AJAX requests. In your code use the following form:
setInterval(function() {
$.get('notification.php', checkJobsCounter); // returns jobs count in plain text
}, 30000);
Well you need to make an AJAX call and the response of it should be the number of new notifications. Now check if num>0 then just do $("#notification").fadeIn(); which is a by default hidden div having text You have new notification (or whatever) and a close button.
$(doument).ready(function(){
setInterval(function(){
$.get("notification.php", function(data){
if(data>0)
{
$("#div").fadeIn();
}
});
},1000);
});
Once user closes this you can create a cookie in the browser of the user and then check if cookie is set dont make ajax request, This was you dont have to update the db and every user will be able to see the notification.

How to display a 'live' count of total files uploaded?

I am looking to display the total number of files in a database. To clarify, say I had a website where people could upload pictures of their cars, and I wanted to display a live number of how many pictures there are, what would be the best way to do this? Javascript, php? A mix? I envision a div with a number saying "Total Pictures: x" and where x would be whatever the live total is. I plan on using MySQL to store all the data on the website. Is this even recommended to have something communicate with the server this much? Is there a name for displaying a live number? Thanks!
If you are thinking to use the AngularJS way, you could create a Poller service which polls every second (assuming your /counter.php returns json):
app.factory('Poller', function($http, $timeout) {
var data = { response: {}};
var poller = function() {
$http.get('/counter.php').then(function(r) {
data.response = r.data;
$timeout(poller, 1000);
});
};
poller();
return {
data: data
};
});
Then your controller:
app.controller('CounterCtrl', function(Poller, $scope){
$scope.counter = Poller.data;
});
And finally in your view:
{{counter.response}}
You can read more about $http
Set up a PHP script that queries the database and returns the total file upload count. After that, you can use JavaScript on the page to periodically call the server in a specified interval of time and fetch the count data from your PHP script. Using jQuery and GET, you can do something like this:
jQuery(function($){
setInterval(function(){
$.get( '/counter.php', function(fileUploadCount){
$('#counter').html( fileUploadCount );
});
},20000); // 20 seconds
});
In your HTML:
<p><span id='counter'>xx</span> files have been uploaded so far!</p>
Hope this helps!
How live do you want it to be? Just whenever someone updates the site it's going to have the new value or do you actually want it to update in near real-time?
If it's the latter you have to use Javascript against some kind of API that returns the amount of files in the database. I can't help you with that bit since you are using PHP, but it shouldn't be too hard. Just return some JSON looking something like
{ fileCount: 45020 }
Client-side you have a few options. You have the different javascript frameworks like AngularJS and EmberJS (and many more), as well as just 'plain old' javascript and frameworks like jQuery
The keyword is really AJAX, even if that is just a sort of buzzword for using javascript to make websites dynamic.
I am a fan of using AngularJS because it's easy, but I'll try to give you some pointers for using jQuery first. Note that I have not used jQuery in years now.
The jQuery way
jQuery has a function called jQuery.getJSON(), and according to the documentation you can use that function something like this:
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON( "http://example.com/api/fileCount.json")
.done(function(data) { console.log(data) })
.fail(function() { console.log( "error" ); })
.always(function() { console.log( "complete" ); });
So this means we can call an endpoint and fetch some data using jQuery.
Here is a link to a tutorial about the basics of jQuery by the way.
jQuery makes us able to do things like this:
<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>
When that is executed the div with id "divTest1" will contain the text 'Hello, world!'.
That sounds like something we could use here!
Javascript also has this really nice function called setTimeout(), which allows us to make it call a function later.
This describes how to use jQuery with setTimeout()
As you can see it also shows us jQuery.documentReady(), which is an event that fires when the website is finished loading, so it is a good place to put code we want executed.
The example below shows how to use jQuery to hide a div with id=div after 3 seconds.
jQuery(document).ready(function () {
setTimeout( "jQuery('#div').hide();",3000 ); //hide a div after 3 seconds
});
Combining these things you should be able to make a repeating call that fetches data from your server and then updates a div or another element with the data you have fetched.
Just create a function which uses jQuery.getJSON() to fetch data, and then at the bottom of that add a setTimeout call to run itself in X seconds (however often you want it to update).
In jQuery.documentReady() you call that function the first time the document loads.
And in the .done() bit of the getJSON() call you add the data you got from the server to your div with whatever html you want. I showed you how to use $("#divTest1").text(), but there is also a .html() which acts the same but you should use it to add html to a element.
The angular way would be to use AngularJS's $http to do the same thing, but I wouldn't recommend learning AngularJS until you have a bit of a better grasp on Javascript.
When you do though, I highly recommend it. It's a much better approach than using jQuery.
You can read about AngularJS here
I hope this helps!

How to refresh a div everytime a database is updated?

I am trying to make a chat room on my website, I am using php and mysql to store the messages and all the info. How could I automatically refresh the page every time someone updates the database? example:
If I am on my site, the messages show up on my screen but I can only see more recent messages after I refresh the page. Is there a way to make it real-time?
Also I do not know much javascript/ajax/jquery or any of that. Any help is appreciated!
There will be low amount of traffic on my site. Probably around 10-15 people at a time, if that even.
Your best bet is to make an AJAX request every sec or so and see if there are new messages.
You probably do not want to be reloading the page every time. My recommendation, and there are many ways to do this, is to make a ajax call every so often and check/pull the new information from the database.
I would research AJAX and do a tutorial.
This would be accomplished through ajax by calling a function and updating the div. I would not suggest making people refresh a page everytime they send a message it would get ugly. Another option would be using HTML5 web workers
http://msdn.microsoft.com/en-us/hh549259.aspx
You are going to need to learn AJAX in order to make this work well, and jQuery is probably the easiest way to do it. If we can assume that the DIV you want to update has the ID PonyRides, you would want to do:
$("#PonyRides").ajax({url: "/chat.php?getupdates=true"});
This will get the contents of chat.php and stick it into the #PonyRides DIV. This assumes that chat.php will get the contents of the database and format them into HTML.
The remaining challenge is to make it update whenever your database does, but the simplest way is just to reload the whole chat regardless of whether an update has been made or not.
That will impact performance, but if you have less than a hundred chatters you'll probably be fine. If you have more than that, you'd do well to sense inactivity and decrease the checking period, or only send updates instead of the whole chat. Those are more complicated topics, though, and you can build them in as needed once you get these basic concepts down.
To do this, simply wrap the ajax() call in an interval like so:
setInterval(function(){ //the following code runs repeatedly
$("#PonyRides").ajax({url: "/chat.php?getupdates=true"}); //update our chat div
},5000); //repeat every five seconds
The other, awful method would be to load chat in an iFrame, set to reload periodically using the meta refresh technique. This would be dreadful, and can only be recommended if you are trying for some reason to support incredibly old browsers.
You can use AJAX request to update the values
<script type='text/javascript'>
// function for making an object for making AJAX request
function getXMLHTTPRequest() {
try {
req = new XMLHttpRequest();
} catch(err1) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (err2) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (err3) {
req = false;
}
}
}
return req;
}
var http899 = getXMLHTTPRequest();
function searchFabIndia() {
var myurl = "http://my2nddomain.com/yebhi.php";
myRand = parseInt(Math.random()*999999999999999);
var modurl = myurl+"?rand="+myRand;
http899.open("GET", modurl, true);
http899.onreadystatechange = useHttpResponse899;
http899.send(null);
}
function useHttpResponse899() {
if (http899.readyState == 4) {
if(http899.status == 200) {
// do all processings with the obtained values / response here
// after doing the stuff, call fn again after 30 s say
setTimeout("searchFabIndia()", 30000);
}
}
}
</script>
<body onload='searchFabIndia();'>
I would suggest making an AJAX request to a file on your server which will update the database. If the update to the database is successful then return the message which was updated. Back on the client side you wait for the response and if you get one then append the message to the end of the content. This way you're loading all the messages every time (which would be expensive), you're only loading new messages.
There must be something similar to SignalR(.net) for php. It lets you add code when an event occurs, I think that is what you are looking for.

Auto Update Stats From SQL Database

I'm trying to get an effect like the http://www.minecraft.net page where it auto updates sales from a database, I've been researching this for two months now and no luck.
I have a php file which finds how many results are in a database and displays them as a number, works fine http://tzeale.com/sandbox/stats/pull.php
What I'm trying to do is get the effect like minecraft.net where it auto updates without refreshing the page. Could anyone guide me on what to do? I don't know what else to try.
Thanks.
hYou need to use AJAX.
setTimeout, alongside a AJAX call to that pull.php
If you are using jQuery, here is a good example on how to achieve what you want.
Added a simple logic to see if the server is dead, and eventually stop.
var failed = 0;
var limit_failed = 5;
(function updateSales( waitTime ){
waitTime = waitTime || 1000; // Set to 1 second by default
setTimeout(function(){
$.ajax({
url: 'pull.php',
success: function( response ){
// Update something with your response
alert ("sales are now at: "+ response);
updateSales(); // Recursion
},
error: function(){
// Error handling - not necessary
// If the request failed more then (limit_failed) times, you might want to stop it from checking after (limit_failed) times,
// and in the meanwhile icnrease the wait time, so the server has more time to get back online.
if( ++failed < limit_failed ){
waitTime += 1000;
updateSales( waitTime );
}
}
});
}, waitTime);
})();
You would use setTimeout and Ajax. setTimeout would get the data every 1000 ms (or however you set it) using Ajax to get the data.
You would wrap your display count in your html like this for example:
<span id="mycount"></span>
Then your jQuery code would look something like this:
setTimeout(function(){
$.get("/sandbox/stats/pull.php",function(data){
$("#mycount").html(data);
});
},1000);
1000 is one second, you can change it if you'd like. I don't know how to make it animate like that, but it would go inside your $.get() function once you retreive the data. Also this must be on the same domain as http://tzeale.com/ for the Ajax to work due to same origin policy
HOWEVER, After reviewing te minecraft.net site, I noticed they are loading this data into their page one time, instead of getting it every 1 second:
<script>
var justLoggedIn = false;
var totalUsers = 33652552;
var paidUsers = 6495707;
var totalUsersRate = 1.2166667;
var paidUsersRate = 0.15;
</script>
Then they are not getting live data with this. They are just getting the current amount, then keep adding 1 to it.
They make it animate using this plugin: http://timeago.yarp.com/
And still using setTimeout() to keep adding 1 to it every second. I don't think this is real users, just a counter starting at the var totalUsers

Ajax time alert using PHP

I have an issue here: I am creating a project that involves planning. A user plans a specific program for a particular time and submit into the database, MySQL, using PHP.
I want the system to raise an alert when the time planned has reached or when it is a few minutes to the time.
Something like
if ($selectedDate==CURDATE() $$ selectedTime==CURTIME()){
// some ajax to provide popup
}
I will appreciate useful help. Thank you.
You will need to create a global variable to store your list of events, not sure what type you would want to use. You will fill the variable from an ajax call (so you can do it on every page of your app), and then iterate over the events to prompt the user.
On page load, you will want to grab the events from your database.
$(function()
{
retrieveEvents();
promptEvents();
});
Create a function that can be called to get the events, and store them to a global variable.
function retrieveEvents()
{
// Make ajax call to get all events
// Wait 1 minute, calls the function again to get new events
setTimeout( "retrieveEvents()" , 60000 ); //60000 = 1 minute
}
You will then want a function to then prompt the events
function promptEvents()
{
// At this point you will iterate the global variable of events
// You can check if the event is 2 minutes away, or 5 seconds away
// In those cases, you would then show a modal or alert box.
// Wait 5 seconds, call this method again
setTimeout( "promptEvents()" , 5000 ); //5000 = 5 seconds
}
You could try to run a repeating ajax call (using javascript setTimeout) and on your second page run a query on the database to retrieve their stored "plan time" and test against current time. If it is nearing (e.g. 2 minutes away or something) then your ajax call will return a warning.
Use javascript's setInterval function to check whether the time is closer. Example:
setInterval(function() {
// ajax request and alert action goes here
}, 1000);
The ajax check in the above example will execute in every 1 second (1000 milliseconds). You can change the interval as you like, say 5000 (5 seconds).

Categories