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

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

Related

jQuery AJAX - Get data from php during the request

I'm using AJAX to insert data in MySQL database. During the AJAX request, there is a PHP function that loops inside a JSON array in order to get data and to insert it inside the DB. Everything works fine.
But, I would like to know if there is a way to pass, during the AJAX request a PHP var to jQuery in order to append it in HTML or to retrieve the data with console.log. I can get these info on AJAX complete but is it possible to get info during AJAX request?
I think you can just echo the php var on the page?
E.g. echo "<label>".$phpVarToAppend."</label>";
Nope. HTTP is stateless. You make a request and you get a result.
You must use different techniques to check the request's processing advancements from server.
Given that you store a record of the progression during the processing somewhere (db, cache or whatever), the simpler trick is using another AJAX call to a simple function that returns the last processing record.
This is a traditional polling mechanism.
A more advanced solution could be using a different connection upgraded to websockets. This will be a true realtime channel.
On top of these there's a world of possibilities. It only depends on what you need to manage with your POST request and how long does it take the processing.
For big payloads it's usually better to return immediately and start processing in a different task. (and thus a pooling mechanism to check progression)

jQuery .get() data from JSON formatted data and refreshing some DOM element to display it

I have heard about technologies like socket.io, but it is too advanced for me.
I created PHP file that displayes JSON formatted data in array.
I use the jQuery function .get() with the URL datafile.php to get the string and display it in the pages. I use timer loop for this .get() and it is run every few seconds. This is how I simulate updating texts without refreshing the page.
But I really think if it is the right way of doing this. is there some better approach?
Here is my current script (the highlights classes are only to make little flashing on the element to show that value has been changed):
setInterval(function() {
$('.total-xp .number').addClass('highlighted');
setTimeout(function() {
$('.total-xp .number').removeClass('highlighted');
}, 1500);
$.get("data.php", function(data) {
$(".total-xp .number")
.text(data.total_xp_data)
}, "json");
}, 10000);
Two comments. You should look at socket.io. Socket.ios allows your server to push data updates to subscribed clients when they happen, thereby saving on wasteful polling for updated data from every attached client, this is pretty much accepted practice. I've no personal experience on socket.io however I've use Signal R in .NET for these kind of problems and found it works well.
Second. I would be tempted to return json to your client, then your client can render the data as appropriate. Then if you need another interface to present the data you don't have to write another server side method, or if you need to change your UI you don't need to reploy the server side components.
If your really can't face the effort of socket.io then your solution will work, it will be hard to get anyone to agree it is best practice.

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.

javascript vs. php : pros and cons for code development

If a user refreshes a page I need to send the data using php as it accesses a mysql table.
If the user adds content, I don't want to run an AJAX call "first" as I can simply and immediately update the DOM, and then send a one-way ajax call to store it in the mysql table.
So on a referesh I have PHP creating my XHTML and sending it to the Browser.
On user input, I have the DOM update immediately followed by ajax call to put it in the mysql table.
Thing is I have to write code in JS and PHP for each user action that modifies the page.
Should I have the data sent to the Javascript for entry into the DOM and not do less with it in the PHP. What are the tradeoffs from taking user input and converting it to the UI with javascript vs. php?
Should I offload as much as possible to the client to reduce server load?
You have answered it yourself:
With php you need to send it through ajax and wait for response
With javascript you need to maintain 2 set of templates (server- and client-side one)
If you need to do something with the data serverside (validation, processing, etc), you can either use JavaScript with AJAX, or send it off on a page reload using POST or GET, depending on what you're sending. If you don't need to do anything with the data serverside, then using JavaScript to modify the DOM immediately is fine.
DOM operations aren't fast. Try it and you'll see that is better for your users to pass real HTML as it is or JSON-embedded with AJAX requests. Even big names like Twitter do it so.
If you still want to get away without PHP consider server-based JavaScript, e.g. Node.js.

jQuery AJAX get PHP script, display the content as it loads

I'm having to interact with the Facebook API for this project, which I find to be actually a bit slower than I expected. Because of this, I'm having to do something which I find rather unorthodox: I need to load the content Facebook provides back in my PHP script AS IT LOADS from Facebook. Traditionally I've loaded content into a div tag at the success of the script; however, I need to load the content as it appears. It would be absolutely unacceptable to have a client wait nearly a minute for Facebook to load an album and all respective comments before displaying anything. Hopefully I'm not being to vague; I'm not here to ask for code, but I've tried just about everything I can think of. Is this a simple concept I'm missing?... I feel as though this is easier than I'm making it.
I'm using jQuery AJAX as I find this easiest to work with. Any comments and/or help would be greatly appreciated.
The root of your problem is that jQuery's AJAX methods hook into the onreadystatechange event and readyState variable. readyState is only set to 4 when the file is completely transferred, and therefore your events will only fire after the download is complete.
Accessing the data as it is being sent is not consistent across different browser families. Doing it this way is going to be incredibly complex and time-consuming. I would recommend first doing this a little differently, perhaps by preloading the relevant facebook data on your own server predictively. This can be compiled to a static page, and that can in turn be served to your users very quickly.
To get the data to your users faster, you'll need to work outside the box as well. There's a jQuery plugin discussed here ( Does PHP flush work with jQuerys ajax? ) that makes jQuery ajax methods compatible with streamed output. Good luck.
The problem seems to stem from the fact that you're getting too much data at once. I suppose you are talking about receiving content from ajax as it is printed out immediately, but it is possible this content is built and sent at once and you won't have access to the data until the entire parse is complete. If this is untrue, look into COMET. If it is true, the solution is to put a limit on how much data you retrieve at once in an effort to reduce the parse time. For example, retrieve 5 photos in each request. Add those 5 photos to the DOM while you retrieve the next 5.
Instead of putting whatever code you want inside of the callback, just put it after the callback
for example
$("#div").load("facebook...", function() {
//do stuff
});
//put the stuff you want to load at the same time, here

Categories