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.
Related
I want to ask is there a way to track database table using php mysql.
I want to do something like i have a table called post. Now when user post some data other user need to view this data. That is latest one need to be view to user on the top. We can do this by refreshing div after every few sec or using ajax. But can we use Trigger. As we know it automatically fires when something is executed. Hence i want to know can we use trigger in PHP code to automatically detect changes in table. And when a new post is available it needs to return the data from database. Please give me a brief description about this. Thank you in advance.
The trigger is executed on Mysql Server, not on the PHP one (even if those are both on the same machine).
So, I would say this is not quite possible -- at least not simply.
Still, considering this entry from the MySQL FAQ on Triggers :
23.5.11: Can triggers call an external application through a UDF?
Yes. For example, a trigger could invoke the sys_exec() UDF available at MySQL Forge here: http://forge.mysql.com/projects/project.php?id=211
So, there might be a waty, actually, via an UDF function that would launch the php executable/script ; not that easy, but seems possible ;-)
Read more about it in:
https://stackoverflow.com/a/1467387/3653989
SQL trigger is a database object executed server-side.
You want a front-end technique to refresh your data without refreshing the whole page.
You can refresh your page using:
<meta http-equiv="refresh" content="5">
With PHP, you can refresh the page using:
header("refresh: 3;");
but no-one would suggest you to use such a method, because your need is refreshing the page, only after a change in your database, and not continuously.
So, if you already use PHP, you need Javascript Push technology:
Push, or server push, describes a style of Internet-based communication where the request for a given transaction is initiated by the publisher or central server. (wikipedia)
JavaScript polling, long-polling, real-time techniques, and javascript frameworks such as jquery, node.js, socket.io include a lot of practices that give you this possibility.
I have a project that needs a sort of shopping cart that is always available at the top of the screen. Whenever someone hovers over the "cart" icon, a list of everything that's inside is shown.
However, if an user has two tabs of my site open, and in one of them something is added to the cart, the other one will be outdated and a refresh will be required.
My question is: if I use AJAX to constantly update the list of items (which will require sessions and database checks), will it be a big enough load on the server (or even on the browser) for it to be a problem, or is this common practice? If it is a problem, what other ways can I go so every tab an user opens is always updated?
If someone could show me the path so I can study more about it, even the name of what I should look up, I would be really grateful. Thanks.
there is no load on browser, just one more request in server ... maybe these requests are useless,
there is another way name server push
APE (Ajax Push Engine) :: Comet server :: Real time data streaming ->
http://www.ape-project.org/
nginx_http_push_module - Comet For The People -> http://pushmodule.slact.net/
node.js -> http://www.nodejs.org/
Socket.IO: the cross-browser WebSocket for realtime apps. ->
http://socket.io/
Comet with Nginx and jQuery | Coach J ->
http://blog.jamieisaacs.com/2010/08/27/comet-with-nginx-and-jquery/
if your request count is more than your server power use this way but if you have little request and not important you can use server pull frequently
Ajax is the solution here - it has a very light footprint.. as long as you don't use it indiscriminately, it is pretty much the same as reloading the page (much less if done correctly as its serving a smaller document). In fact, research has shown that ajax can cut the server bandwidth usage by over 60%.
You can read about the speed issue specifically here.
I learned Ajax over at Tizag, they have a brilliant Tutorial.
Hope this helped :)
you can make the ajax call on an interval to load the div with latest data. Something like this
(function getLatestCart(){
setTimeout(function(){
$("#latestCart").load("getCartDetails.php", getLatestCart);
}, 10000);
})();
this will call the method on every 10 sec(you can change the time interval) and load the latest cart to the div with id latestCart.
You can track locally this changes.
Use UserData (IE7 and down) or domStorage with updated data, and check every 10-20 seconds if the data was changed.
So I developed this web application, which has several multiple select boxes on an admin page - each of these boxes contains multiple values, which we will call criteria.
The criteria in these boxes are generated on a form on another page and stored separately in another table in the database. The big problem is that my boss wants to have a new criteria editing page pop out in a new window, or a different tab of the same browser, allow the user to add one or multiple criteria, and have these update in the main admin browser window in real-time.
Now, if it was in the same window, my immediate thoughts would go to AJAX. However, because it will be in two separate browser windows, I don't believe this is a feasible solution.
Is there anyway (other than some form of COM programming or other OS-y methods, which I don't want to get into) to pass a value between the two browser windows, without having to reload the main page? That is a critical issue here - the main page cannot be reloaded at all during this process.
Would frames be the answer (thus getting rid of the dual browser window problem by not having two windows)? Something else? This is beyond my range of experience.
Possible solutions:
Frames (probably the simplest, works with old browsers too)
Comet (emulated JavaScript push notifications)
Mootools Request.Periodical
HTML5 Web Sockets (the "best" but works only in the newest browsers)
Well, you might be able to look into fsockopen() and see if a php socket solution could be useful in this case, but that may not be necessary since the skill level of sockets is - in my opinion - considerably higher than running a basic ajax request in your new frame to check if the form has changed within the last 5 seconds.
You can create a table in a database to represent a user's form and store the current values in that table along side a token that regenerates on each update. That way when you pop up your new screen that is supposed to live update you also send the form id and the first token. Then that window makes a basic ajax call every 5 seconds to see if the token for that form id has changed since the last call. If so, return a json object with all the info you need and update accordingly. If not, return false and do nothing.
This is just one possibility. It might be a lot of unnecessary db calls but then again - I don't know the purpose of this request so I don't know how absurd this solution is relative to your needs.
I stumbled across a usage of the localstorage (DOM storage) API for sharing messages across windows. I don't know how much data you need to send, and there are some compatibility concerns (support in IE starts in IE8, other browsers have good support for some versions now). Basically, each page would have an "onstorage" event handler set, so that a modification to a store (add, delete, modify/update) in one window would trigger the event in the other window as well. Of course, this is limited to the same origin. From how you described what you need, this sounds like it might be a valid solution.
Once you open a window using
var new_window = window.open(...);
then new_window is a reference to the window object in the new window, and from the new window window.opener is a reference to the window object in the original window. Subject to the same-domain security policy you'll be able to call functions "across the divide"
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
I am a little bit new to the PHP/MYSQL arena, and had an idea to be able to interact with my Database by using a hidden Iframe to run PHP pages in the background(iframe) on events without having to leave the current page?
Good? Bad? Common Practice? Opinions?
This is most of the time bad, but sometimes inevitable.
The common practice to do it is to use AJAX, it's so common that even W3School has an article about it.
The advantages of using AJAX over IFrame is that AJAX can be multi-threaded. You can send several requests in a row, which is more troublesome to implement with IFrames. Moreover, AJAX supports status code so you can detect errors, where with IFrames you'd have to rely on scraping the page's HTML and hope you've determined the correct status by looking at the error page's HTML code.
AJAX is more JavaScript idiomatic and event driven, which means your callback will get notified automatically when there is a response. With IFrame you'd have to setTimeout() and keep polling the IFrame for a response, which may break easily.
IFrame is sometimes inevitable in cases like where you want to upload a file without leaving the current page. But that's probably not your scope since you mentioned only database interactions.
Learn to use XMLHttpRequest, which is the foundation of AJAX. After you've become familiar with that, try making it fun by using a JavaScript framework such as jQuery, Dojo, etc.
I'd guess something is supposed to happen when your database does something, right? I.e. your page should give some sort of feedback, maybe update a number or some text.
So you're going to use Javascript anyway. In that case, skip the iframe and just send off AJAX requests.
This is commonly accomplished using AJAX. The jQuery javascript library makes this easy
I don't think using iframes is a good way to accomplish this. You would still need javascript enabled to change the location of the iframe, and if javascript is available, why not just use AJAX?
If you use the iframe, you wouldn't be able to receive a response from the server in any meaningful way without doing a lot of workarounds. For example -- using jQuery, you could submit some information to the server with a single function call, and then when that request completes, a callback function can be invoked with response information from the server:
$.post("ajax.php", { var1: "data", var2: "moredata" },
function(data){
alert("Server says: " + data);
});
In this example, when the request completes, an alert box appears with the output of ajax.php.
With an iframe, you might do something like change the location of the iframe to server.com/iframe.php?var=data&var2=moredata&var3=moredata, then wait for a bit, and grab the contents of the iframe (if this is even possible) and do something with that.
Not to mention, when you run into problems doing this, you'll probably ask for advice on SO. and each time, people will probably say "drop that and use jQuery!" :) may as well skip all the pain and suffering and do it the Right Way to begin with
The hidden iframe method was used before the adoption of XMLHttpRequest api (Maybe you have heard of it as Ajax).
Years ago I was using a former implementation using rslite but nowadays this technique has, to me, just an historical value.
You can get directions on using Ajax techniques in plain javascript at http://www.xul.fr/en-xml-ajax.html or, better, you can choose to use a common library, jquery or mootools among others, to deal with the different implementations in different browser.