Grabbing data from MySQL using PHP realtime? - php

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.

Related

Why to use ajax to send a PostgreSQL query to a server?

I have a web application where I actually use JQuery and Ajax in order to send a query to my database.
My script is something as simple as this:
$(document).ready(function(){
var datastr = id; // get the value inserted in text
var ajaxurl = 'run.php', // script to run
data = {datastr:datastr}; // data to pass
$.post(ajaxurl, data, function (response){...//do something
Making some improvements in my script it crossed my mind this: do I really need to make an Ajax request to send this query to the database or I can just use something as simple as the PHP function for PostgreSQL to do that?
Ofcource I know that Ajax is all about asynchronous communication but I want to know what would be the best practice in a situation like this. Is using Ajax in this case an overkill?
do I really need to make an Ajax request to send this query to the
database or I can just use something as simple as the PHP function for
PostgreSQL to do that
Well actually it does not have the same goal. As you may know, Ajax is client-side meanwhile PHP is server-side. If you want to send your request without refreshing your webpage, then you would need asynchroneous request like Ajax does. Else, PHP fit your need.

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

The overheads of using setInterval to get latest data from database

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.

How can I have live info on a page without refreshing?

Facebook has introduced a ticker which shows live news scrolling down. How can I have this same time of functionality on my site? I don't care to use an iframe and have it refresh because it will A flicker and B make the page loading icon come up (depending on browser). How can this be done?
For this you'd want to fetch the data you're looking for with AJAX every X seconds.. Also known as polling.
Here's the break down: Every X seconds, we want to query our database for new data. So we send an asychronous POST to a php page, which then returns a data set of the results. We also declare a callback function (native to jQuery) that will be passed the data echo'd from our PHP.
Your PHP:
if (isset($_POST['action'])){
if ($_POST['action'] == 'pollNewData'){
pollNewData();
}
}
function pollNewData(){
$term = $_POST['term'];
$sql = "select * from TABLE where TERM = '$term'";
$result = get_rows($sql);
echo json_encode(array('status'=>200, 'results'=>$results));
}
Your front end javascript:
setTimeout(pollForNewData, 10000);
function pollForNewData(){
$.post('url/ajax.php',{
action: 'pollNewData',
term: 'your_term'
}, function(response){
if (response.status == 200){
$.each(response.results, function(index, value){
$("#container").append(value.nodeName);
});
}
}, 'json');
}
What essentially is going on here is that you will be posting asynchronously with jQuery's ajax method. The way you trigger a function in your PHP would be by referencing a key-value item in your post depicting which function you want to call in your ajax request. I called this item "Acton", and it's value is the name of the function that will be called for this specific event.
You then return your data fetched by your back end by echo'ing a json_encoded data set.
In the javascript, you are posting to this php function every 10 seconds. The callback after the post is completed is the function(response) part, with the echo'd data passed as response. You can then treat this response as a json object (since after the function we declared the return type to be json.
Pretty much the only way you can do it is with some sort of Asyncronous javascript function. The easiest way to do it is to have javascript priodically poll another http resource with that information and replace the current content in the dom with the new content. Jquery and other javascript frameworks provide AJAX wrappers to make this process reasonably simple. You aren't limited to using XML in the request.
It's a good idea to make sure that even without javascript enabled that some content is available. Just use the javascript to 'update it' without having to refresh the page.
You can do this kind of ticker using Ajax... using AJAX you can poll a URL that returns JSON/XML containing the new updates and once you get the data, you can update the DOM.
you can refer this page for introduction to Ajax.
Ajax is the best method but that's what everyone else already mentioned. I wanted to add that although I agree ajax is the best method, there are other means too, such as Flash.
There are two approaches possible for obtaining updates like this. The first is called push and the second is called pull.
With push updates, you rely on the server to tell the client when new information is available. In your example, a push update would come in the form of Facebook telling your site that something new happened. In general, push schemes will tend to be more bandwidth friendly because you only transmit information when something needs to be said (Facebook doesn't contact your site if nothing is going on). Unfortunately, push updating requires the server to be specially configured to support it. In other words, unless the service you are asking for updates from (ex. Facebook) has a push update service available to you, you cannot implement one yourself. That's where pull techniques come in.
With pull updating, the client requests new information from the server when it deems necessary. It is typically implemented using polling such that the client will regularly and periodically query the server to see what the latest information is. Depending on how the service is oriented, you may have to do client-side parsing to determine if what you receive as a response is actually new. The downside here is of course that you likely will consume unnecessary amounts of bandwidth for your polling requests where no useful information is obtained. Similarly, you may not be as up-to-date with new information as you would like to be, depending on your polling interval.
In the end, since your site is web-based and is interfacing with Facebook, you will likely want to use some sort of AJAX system.
There are a few hybrid-ish approaches, such as long polling via Comet, which are outlined rather well on Wikipedia:
Push technology: http://en.wikipedia.org/wiki/Push_technology
Pull technology: http://en.wikipedia.org/wiki/Pull_technology

Retrieve Database Value Without Page Load AJAX/PHP/Facebook Style

I am wondering if anyone could show, or explain with examples, how facebook checks its database for new messages? It seems to do it periodically, without loading the page. What would be the best way to achieve this in a PHP/MySQL/Jquery script?
Any help is always appreciated!
Cheers, Lea
you can do this: usign periodical updater
<span id="inbox-title"></span>
<script>
$.PeriodicalUpdater('/path/to/service', {
method: 'get', // method; get or post
minTimeout: 1000, // starting value for the timeout in milliseconds
maxTimeout: 8000, // maximum length of time between requests
}, function(data) {
$('#inbox-title').html('you have ' + data + 'new messages');
});
</script>
another option is to bind the onmousemove event and make the ajax call when than happes
There is actually a "page load", but it's a hidden request that doesn't reload the displayed page. Take a look at the jQuery Ajax command documentation for more details on one of the simplest ways to accomplish this (especially since you already mentioned using jQuery).
Have a look into reverse ajax with the COMET technique, this is a perfect use for it.
The idea behind it is to start an ajax request and let it timeout which could be 60 seconds, when it times out, start it again, here the browser has a (nearly) persistent connection to the server, if (for a simple example) a message gets created for a user. the server can reply to one of the hanging ajax requests that have been made (in this case by the recipient of the message).
No data is transfered while the xmlhttprequest and the server are waiting, but closing and reopening connections might be a burden on your server.

Categories