The overheads of using setInterval to get latest data from database - php

im creating a messaging feature that gets the latest messages from a database every few seconds, basically this method does a continuous database search in order to display new messages.
example of the code:
function getLatestActivities(){
var ignoreMessagesArr = $("input.activityId").map(function(){ return this.value; }).get().join(",");
var profileId = $("input#userActivityId").val();
$.ajax({
traditional: true,
dataType: "json",
type: "GET", url: "include/process.php",
data:{
getLatestActivity: "true",
toUser: profileId,
ignoreMessages: ignoreMessagesArr
},
success: function(data){
$.each(data, function (i, elem) {
$('.commentMessage').after(elem.value);
});
}
});
}
What I want to know is whether there is a more efficient way of performing this task, i.e. detecting a change in the database instead(???).

It sounds like you want your web app to receive data when it changes in the database, but not necessarily to send data in real time. If two way communication is required then you are looking for Web Sockets which Socket.IO will help you with server side but requires that you run a Node server. There is a Google code project that enables Web Sockets for PHP called PHPWebSocket but, if I remember right, requires that you run it in a separate process (i.e. run it from the command line). So that kind of takes care of the server part, but now you have to worry about the front-end.
Currently only FireFox and Chrome fully support Web Sockets according to CanIUse. For those browsers lacking support you need a polyfill. Here is a list of HTML5 polyfills. So Web Sockets can be sort of a mess to implement, so make sure that's what you want to do.
On the other hand if your webapp only needs to receive data then EventSource (a.k.a. Server Sent Events) is the way to go. The support is better on the front-end and you don't really have to do much on the server. Again, for less than stellar browsers you will need a polyfill, but that pretty much just means IE. See the following sites/tutorials on how to use this feature.
http://my.opera.com/WebApplications/blog/show.dml/438711
http://dsheiko.com/weblog/html5-and-server-sent-events
http://www.html5rocks.com/en/tutorials/eventsource/basics/
If none of that works there are a few options. Constant polling using some kind of repeating structure like setTimeout, long polling (a.k.a. hanging get) where the server leaves the AJAX request open until there is new data, and there's also the infinite iframe trick, or maybe even a Flash plugin that connects to the server to get data.

You might want to look into Socket.IO it's geared toward realtime communications with the server. Then you can design the backend to push data to the client when it's available rather than constantly polling the database for new information from the frontend

HTML5 Web Sockets allows for two way communication between the client and your server...

In my opinion you should request only the last ID inserted in your database and add it as a parameter to to your ajax request.
process.php should handle that ID and if there are other rows to do the search.
like
$query = mysql_query("SELECT `ID` FROM `table` WHERE `ID`>'$lastId'");
$result = mysql_num_rows(); //use that to see if you have new rows.

Related

Use AJAX to update page when new row is added to table

I am in the process of learning AJAX, as I need it for a current project. I have a feed which I want to update live when a new row is added to a MYSQL table. I've actually done this with node.js, but unfortunately my clients server can't use NODE, so I am trying to see if it's possible with AJAX.
Thank you for your help!
There isn't any way that i know about where MYSQL or PHP can push updates to a page when it is updated.
The best option would probably be running timer with javascript and check the database periodically to see if there have been any updates,
var refreshId = setInterval(function() { checkforUpdates(lastIndex) }, 10000);
Pass in the last row of your table index to the javascript function and the function makes an ajax call to a PHP that queries the database for any new rows, if any updates returned, add them to the table with javascript.
If you are also looking to check for updated rows, that gets a bit trickier!
You'll need to have the client either contact the server constantly via polling, or use a push technique such as comet or websockets. Otherwise your client has no way to know when new data has arrived.
Comet and websockets allow for the most real-time feel to the process since they actually send the data to the user client (your connected browser) as soon as it is available whereas with polling it's just your browser querying the server on an interval.
Disadvantage is that push techniques and certainly comet which requires a HTTP Keep Alive can be quite heavy on your server, especially for process based servers such as apache, their maximum connections get filled quickly and then held up until disconnect. There are tuning options and modern settings for it but it's not optimal: the problem even has an official name c10k and is one of the reasons you see event based servers gain popularity these days.
its easier to do ajax stuff with jquery
$("#update_charges").live("click",function() {
$.ajax(
{
type: "POST",
url: "phpfile_toadd_updaterecord.php",
data: "passvalue="+$('input_field_name').val(),
success: function(msg)
{
$('#result_div').html(msg); //msg contains any test echoed from //phpfile_toadd_updaterecord.php file
}
});//end $.ajax
}
below can be your html code
<form>
<div id="result_div"></div>
<input type="button" name="update_charges" id="update_charges" />
<input type="hidden" name="input_field_name" id="input_field_name" value="anyvalue_to be passed to php file"/>
</form>
Jquery ajax help page

Refresh content automatically if the database changes

how can I automatically add the value of a database row (PHP), to the page, without refreshing the page itself, when the mysql database table changes?
So, it is a bit like this: Automatically refresh browser in response to file system changes? , but instead of refreshing the browser with the file system changes, update the content, without refreshing anything, when the databse changes.
Thanks. I have tried to make this as clear as possible.
Please note this is outdated answer. Recent ways of doing that is: websockets, server-send events. Nice example of that is Firebase. You can find simple code example in: https://github.com/laithshadeed/wsk-feedback. In this example you will see that updating firebase will send event to the browser via websocket, then the UI will update.
This is called Comet/Reverse Ajax/HTTP server push http://en.wikipedia.org/wiki/Comet_(programming). They are many techniques for doing this as well as many existing frameworks to do it for you.
There are many answers in SO about Comet https://stackoverflow.com/search?q=comet
Simple implementation would be javascript setTimeout and setInterval to check server status, with trigger/stored procedure on mysql.
For depth dive into Comet. There are two cool books about this:
Comet and Reverse Ajax 2008 By Dave Crane
Chapter 4 (River of Content) - Building the Realtime User Experience 2010 By Ted Roden
Update: You may look to the newer techniques in HTML5 like Websockets and Server-sent Events, although IE does not support them well, at the moment Server-sent events is not supported in IE and Web Sockets only supported in IE10
It's not a truly simple task, but it's not that bad. You need a few things working in concert:
A javascript routine on your page that checks with the server at specifiedintervals
A page on your server that reports changes when polled
A callback function on your page that inserts new elements (or updates/deletes existing elements) when changed data is reported by the server.
How you determine which data has been changed is something you will have to think about. The easiest way is probably to have a "modified" field maintained for each record. This way when your javascript polls the server it can include a "last time I checked" timestamp and the server only has to return changes that are more recent.
It's not quite so hard as it may at first appear. Take advantage of prebuilt libraries like jQuery and you can do things like:
$.ajax({
url: 'http://example.com/checkforupdates.php?last=' + (new Date().getTime()),
context: document.body,
success: function(data){
// do something here to add/update/remove elements on your page
// using the information returned in the data argument.
}
});
Manipulate the DOM with JavaScript.

How to display ajax results without ending a php script? Jquery - PHP

I'm using the PHP Imap Library along with Ajax to display search results from within emails. The main problem I am finding is that providers (Hotmail in particular) will cut off connection after 6 or 7 connections in close proximity of time.
Instead of imap_connect() in each script, I'd like to connect once and then continuously display information with ajax. I just have no idea how to do this. The problem is that I need to spit out data through the ajax. Is there any way to return information without ending the PHP program through jquery?
I could also potentially do this if I pass the imap connection variable $connection to the php query instead of calling it, but unsure how to pass it. Here's how I'm currently passing the variables.
var dataString='email=<?php echo $email_address; ?>&connection=<?php echo $connection; ?>&password=<?php echo $password; ?>&server=<?php echo $server;?>&daysago='+daysago+'&num='+num;
$.ajax({
type: "POST",
url: "fastsearch.php",
data: dataString,
success: function(msg){
Link to Imap Connect (and general php imap library):
http://php.net/manual/en/function.imap-open.php
I've done "socket emulation" programming in PHP and jQuery in the past, which is a sort of COMET based approach to keep long connections.
This is really a shining example of where Node.js is favorable to web application development as for the easily installable and usable Socket.io library.
Node.js aside, you have a few options, forking a process that keeps your connections alive and persistent, not connecting live every time someone signs in (use an async task manager like celery), and using a COMET approach which is basically an infinite while loop that constantly spits out data to the client side. The latter would keep a single connection open, but would also be highly unstable, non-performant, and by using PHP the wrong tool for the job.
I'd urge you to reconsider your PHP dependency for this specific task, and instead move in favor to a library that was designed for this specific server push/persistence.

Synchronize Ajax response

I'm in a codeigniter environment and I want to do something like this.
There is a chatroom with a single O-wner and some C-lients.
This is what I'm trying to write
1) C joins the room.
2) when ready, all Cs clicks on a "ready" link that sends an ajax request
3) C waits for all the Cs to get ready, then signals all client and the previous ajax reponses are sent
4) when C receive the response (which should be in the same moments for all the clients) they start doing what-they-have-to-do :)
Is there an easy way to keep track of all the clients connected so that I can signal them all simultaneously?
For now I'm stuck at step 3. I have a code like this
$.ajax({
url: 'myurl.php',
success: function() { doStuff(); }
});
and in my hypotethic file myurl.php i have
while ($this -> MyModel -> waitingQueue) {
sleep(1) }
return "ok";
I guess this is not a good approach since I can't control whether all the clients receive the responses in the very same instane, when I change in my model the variable "waitingQueue".
Thanks all!
You can try to mimic synchronisation with a regular ajax check from all clients on a server. Check the jQuery.queue function, start a queue polling with SetInterval, and then push function containg the checks in that queue (and in theses functions flush the queue).
If you want to go one step further you should get a look at 'Comet' and persitent HTTP connections, trying to put PUSH behavior in HTTP, but it won't be simple :-) At least if you get the complete control of your network, server, people connecting to your app (like an intranet) it will be simplier.
Or you can check documentations on the now closed project google waves.
i recommend using setInterval() in javascript. so you can check continuously for server state.
i don't think you can synchronize your clients that simple. and they will not get the answer from the server at the same time.
if you synchronize the watches of all clients and arrange a collective point in time, when the client shell trigger an event, you might get a good chance.
...and don't forget clearInterval()

Grabbing data from MySQL using PHP realtime?

I am wondering how I would get data from a MySQL database and display it in real time using PHP. Without having to refresh the page. Thanks!
Use AJAX (I suggest using the jQuery library for this), and have your AJAX script (written in PHP) query the MySQL database.
You can use Socket.Io for more Speed ,efficiency and performance for Your Server
http://socket.io/
But you need Node.Js for that
You will have to use javascript. You can use setInterval(function, n) to fire your update calls every n milliseconds, and a library like jQuery to handle the ajax call and updating your page.
Download jQuery or link to a CDN hosted version of jQuery in your page. Then put something like this on your page:
setInterval(function(){
// inside here, set any data that you need to send to the server
var some_serialized_data = jQuery('form.my_form').serialize();
// then fire off an ajax call
jQuery.ajax({
url: '/yourPhpScriptForUpdatingData.php',
success: function(response){
// put some javascript here to do something with the
// data that is returned with a successful ajax response,
// as available in the 'response' param available,
// inside this function, for example:
$('#my_html_element').html(response);
},
data: some_serialized_data
});
}, 1000);
// the '1000' above is the number of milliseconds to wait before running
// the callback again: thus this script will call your server and update
// the page every second.
Read the jquery docs under 'ajax' to understand the jQuery.ajax() call, and read about 'selection' and 'manipulation' if you don't understand how to update the html page with the results from your ajax call.
The other way to continuously update your page is to use a persistent connection, like web sockets (not currently supported across all the common browser platforms) or a comet-style server-push setup. Try googling comet and/or web sockets for more info, but I think the above method is going to be much easier to implement.

Categories