PHP MySQL Requery vs Refresh - php

I have a webpage that run a query on a db and reports the results. Currently the page auto refreshes itself every 10 seconds in order to display (almost) real-time data.
This is probably a very inefficient way of accomplishing this but as of right now I'm not really sure what alternatives there are.
What options do I have to present real-time data on a php webpage?

you can use node.js and socket.io. This is great example to get you started:
http://book.mixu.net/ch13.html
or you can use ejabberd and strophe js library.
I used both of that solution for real time stuff and I found node.js and socket.io much easier to implement.

Depending on what your data is for and how you are using it, ive recently started putting data display functions into seperate pages and then using jquery to load those pages into dives on my main page at page load and then reloading the divs on a timer and on a reload function if the refresh is needed sooner, that way your whole page does not refresh making it flash and go blank but instead the data just gets nicely updated.
var paused = false,
auto_refresh = setInterval(
function()
{
if (paused) return false;
$('#mot').fadeOut('slow').load('motview.php?view1=$dayd&viewdate=1').fadeIn('slow');
$('#work').fadeOut('slow').load('workview.php?view1=$dayd&viewdate=1').fadeIn('slow');
$('#motday').fadeOut('slow').load('motdaylist.php? view1=$dayd&viewdate=1').fadeIn('slow');
$('#notelist').fadeOut('slow').load('notelist.php?dayd=$dayd').fadeIn('slow');
}, 60000);
$(document).ready(function(){
$('#mot').load('motview.php?view1=$dayd&viewdate=1');
$('#work').load('workview.php?view1=$dayd&viewdate=1');
$('#motday').load('motdaylist.php?view1=$dayd&viewdate=1');
$('#notelist').load('notelist.php?dayd=$dayd');
});
function reloaddivs()
{
$('#mot').load('motview.php?view1=$dayd&viewdate=1');
$('#work').load('workview.php?view1=$dayd&viewdate=1');
$('#motday').load('motdaylist.php?view1=$dayd&viewdate=1');
$('#notelist').load('notelist.php?dayd=$dayd');
};
the above im using to display 4 lots of data on one page that all updates nicely on a timer or after ive interacted with a page by calling reloaddivs

Inspect your page carefully to identify exactly what is the data which is to be updated every 10 seconds - chances are it will not be the whole page (menus, navigation, headers, footers).
Cache all that data say, every 10 minutes, or every hour - especially if data driving any of those elements are being dragged from databases.
Then include the panel containing the dynamic data.
Better yet might be to load the dynamic data using Ajax to refresh every n seconds.

Related

Show DIV before refresh

I have a webpage that is auto-refreshed every 240 seconds with the generic HTML Meta tag. During the refresh it pulls data from a database which takes the site about 15 to 20 seconds to build before it's shown to the user. During this time I wish to show a small DIV with a loading message telling the user that it's loading data.
The more complicated thing about this is that the user has a few menu options to filter out specific data from the database. When clicking such an option the page is reloaded again and takes 15 to 20 seconds to build.
Users that aren't familiar with this loading time might feel the need to click the same menu option over and over again within a few seconds hoping that the page will load faster. But instead it will most likely cause the database server to get overloaded with requests.
So, to tackle this I wish to use jQuery to show a loading message, then have it load the data from the database (with a PHP script) and finally dump the data on the page.
I've done something similar but that was limited to users clicking a link which caused a jQuery script to load the data while showing the waiting DIV (using CSS rules).
I can't figure out how to implement this solution for an auto-refresh.
Some help would be nice.
You can use the same solution with auto-refresh as well, with the mention that the initial page load doesn't container the data that requires the DB call, but instead shows a loading message and starts an AJAX call to a server side script that returns the data.
Your page load:
Request
Server query DB
DB Response
Page loads (with data)
Ideal page load:
Request
Page loads (without data) <- loading message here
AJAX call
Server query DB
DB Response
Page updates (with data)
I'd second megawac's comment. Don't use a meta refresh. Also, 15-20 seconds is a very long time for generating a database report that is going to be generated every 4 minutes; odds are that you're bogging down your server pretty badly. Very few queries should really take that long, especially queries that need to be run nearly continually. I would strongly recommend refactoring your queries or doing some caching to speed things up. If you post some code, I'm sure people would be happy to look at it.

Refresh a DIV with AJAX that requires MySQL queries + PHP

I am currently working on a website that is coded primarily with PHP/MySQL and HTML5 as a means to learn the code and become better. I used to work for a forum that used AJAX to reload the latest posts as if the user had just refreshed the webpage, except it just changed the content dynamically without a full reload.
My webpage: http://vgrnews.com
My specific situation is as follows: The homepage loads the four latest announcements and (soon to be) comments from the MySQL DB and displays them soonest -> latest. It is inside of a div called maincontent.
What I want to do: Have the announcements show up dynamically with AJAX regardless of the user refreshing or not. It would probably poll the server roughly every 5-10 seconds.
I don't plan to keep the homepage refreshing like that, but once I add more content it would be good to know how to refresh a div at regular intervals. I have read up on AJAX, but I don't quite understand all of the logistics, they just give you the code and expect you to pick it up. It is hard to morph the code to be applicable for my website if I don't understand it.
Sorry for the long read and thanks for all the replies!
function reload_content() {
$('#latest_post').load('ajax/get_latest.php');
}
window.setInterval(reload_content, 10000);
I will clarify on Alexander's answer for you. What the load() function is doing is performing an AJAX request to the given URL, and then setting the HTML of the selected div(s) to be the returned content. This means that your server should return proper HTML (and only the HTML you want in that div).
You can see http://api.jquery.com/load/ for more information on load().
If you plan on having your server return an JSON (or XML) representation of the information, you will have to use a jQuery get() (http://api.jquery.com/get/), and then process the returned data with a callback.
Note that both get() and load() are simply implicit applications of the jQuery ajax() method (http://api.jquery.com/jQuery.ajax/)
EDIT:
The setTimeout is just making the browser call the function ever x milliseconds. This is what will have it check every x seconds.

Showing Loading Bar for MySQL Query

I am pulling in thousands of records via a single query, and the page takes forever to load. I am trying to show a simple "loading" indicator while loading this in the background.
My loading div is #loadDiv and my info table is #wrapper
What I have currently that is NOT working is:
<script>
$(function() {
$('#loadDiv').hide();
$('#wrapper').hide();
$('#loadDiv').ajaxStart(function() {
$(this).show();
}).ajaxStop(function() {
$('#loadDiv').hide();
});
$('#wrapper').fadeIn();
});
</script>
I am not doing any AJAX calls, so this basically can't work. I am simply loading a query using a while statement. I want to show my loading div $loadDiv while the #wrapper is loading, then once the page is done loading, hide the #loadDiv, and fade in the #wrapper.
Is this possible?
Unfortunately you cannot show a loading bar if the same PHP script is making the query that is also supposed to output the HTML.
If you want to show a loading bar for your query, your program flow should be similar to something like this...
HTML Page is generated and sent to the client
AJAX call is made from the HTML page to a PHP script that queries the database, when the call is made, show an animated loading graphic, and remove it or display a loading complete message when the AJAX request completes (signaling that the query has finished and PHP page returned a result)
Either pre format your data in your PHP script and pass back HTML to your AJAX call, or only pass the data as JSON and manipulate the data on the client side via javascript
It's mildly possible, but it's not possible to do this well. The only way you can have control over the load order of a page (meaning, "display my page layout with a loading graphic, and load the graphic, before you load the other data that's loaded by this SQL query") is by allowing the HTML page to load, and then pulling the results from the SQL select using AJAX.
Doing it the way you're requesting, your best bet (and trust me, this is not your best idea) would probably be to:
Hide #wrapper with CSS
Show #loadDiv with CSS
As early in the page loading sequence as possible (probably just in a script block in the head), set a javascript SetInterval'ed function that checks for something within #wrapper that shows it's finished loading (for example, you could make sure the last value of the SQL result has a particular ID, and have this SetInterval function look to see if that ID exists on the page). Once the SetInterval'ed function finds that ID, you'll know your SQL results are finished loading, and you can have the function perform your fade-in action and then cancel the Interval.
This is going to differ by browser and by the cache situation (browsers have different load orders, and caching of some elements but not others will also affect this displaying the way you hope.) So, it's not really a good option, especially considering how much better some simple AJAX would be for this situation.
Your much better option would be to create a separate page that just displays the SQL results you want, and then use AJAX to pull it into #wrapper once the main page has finished loading. It's not going to be hard at all to learn: http://api.jquery.com/jQuery.get/

Instant MySQL Update from a PHP Page - AJAX?

Had a search, but nothing really suggests a good route for me (might be my bad).
I've built a system to be run on an iPad - and to work as a counter for people entering a venue. Essentially, it's a simple insert into a MySQL database from PHP of a record each time a button is pressed on a web page.
That is, when someone enters the venue, a person on the door presses "In" when someone leaves "Out", an 'in time' is inserted into a MySQL database, and an 'out time' so at any time we can find out how many people were in the venue.
Simples. However, of course, it's quite slow, when multiple people are entering the venue at any one time, so I was wondering how you guys would deal with this. I've looked at AJAX, and I must admit this isn't really my field, but I've had a play. I'm naturally concerned about not losing any data, but also, we can't have the system waiting for 10 secs to reload the page.
My original idea was to have an AJAX 'thing' - which when the 'IN'/'OUT' button is pressed, it calls another PHP page to do the MySQL insert. Is this sensible? Or is there a better way of doing this? As my concern with the AJAX solution is that a new call of that 'insert.php' page, would cancel execution of a previous one, so data may get lost? Am I right?
Any insights anyone has would be VERY helpful.
Thanks in advance.
Ryan
You can achieve this easily using jquery.
First post data from main file and catch data in another file using $_POST['message'], to acknowledge data saved successfully you can output json. Here is example
On your html or php page
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#send_data").click(function(event){
var message= 'This is my message';
sendtodb(message);
});
});
function sendtodb(message){
$.post("save.php",{message:message},function(data){
alert(data.status);
},"json");
}
</script>
Now on secon file where you will save data:
<?php
$msg=$_POST['message'];
mysql_query("insert query");
json_encode(array('status'=>'data saved'));
?>
You'd probably be better to have more than one button on the layout, something like:
IN: 1 2 3 4 5 6 7 8 9 10
OUT: 1 2 3 4 5 6 7 8 9 10
It'd save on the number of requests being sent (and the need to press the same button 10 times).
Other than that, Ajax might be an idea, but you'd need some output to the user so that they know their press of the button has actually done something (as it's not refreshing the page, it's not obvious its doing anything).
But if it's taking that long to reload the page, then the bottleneck might not be because the page is reloading - it could be that the server is getting overloaded with requests (which doing my suggestion above should reduce), or could be the result of some badly written code taking a while to execute.
I think using AJAX is the way forward here, and jQuery does indeed make it really easy. Just a few extra thoughts and ideas:
Potentially a race condition could occur if a user keeps clicking before the ajax request has actually completed, particularly if the server becomes overloaded. I would do what Google search does here, and make sure you keep a record of the previous AJAX request and cancel it when a new one is launched, see this other post
With your back end PHP script, I reckon it's quite likely that this will form part of a larger PHP application. Try to make sure that any other processing that might be done for the front end site, such as building menus for example, isn't done on an AJAX request, because you don't need it and it just wastes processor time.
For more robustness, send a return value from your PHP script which maybe includes a status code, so you can detect if the call actually completed.

Ajax call with MYSQL Update with a delay in the called page

Im currently working on a small search search script build with Jquery and AJAX. Its a live update script that dynamically loads the results in a div.
This is working perfectly but i want to keep track of what answers are being shown. I've tried putting an MYSQL update statement in the results page with a sleep() to prevent updates to the database happening to soon (some questions are shown for .5 seconds, those shouldn't be updated)
Im currently using the follow code:
sleep(5);
$id = $row_rs_results['vragen_id'];
$aantal = $row_rs_results['vraag_getoond'] + 1;
mysql_select_db($database_ruimerleven, $ruimerleven);
mysql_query("UPDATE vragen SET vraag_getoond = $aantal WHERE vragen_id = '$id'");
};
The problem with this is that it slows down the page to a crawl, anyone has a better solution for this? Thanks in advance!
Wouldn't it be better to have a backend process that you send the results to? That way you'd separate the update from the gui front end and it could flush the data to the database at it's leisure. The way your doing it, it would kill performance. Another option is to kick off another process that just does the database update and communicate with it.
I'm not exactly sure what you are going for, but it sounds like you are doing an instant result thing where it brings up results as you type? If that's what you are going for then I would suggest only submitting the AJAX call after the user has stopped typing for a certain amount of time. I would achieve this by putting the AJAX call in a setTimeout, and then every time the user types it resets the timeout.
Example:
var ajax_timeout;
$("#input").keydown(function() {
clearTimeout(ajax_timeout);
ajax_timeout = setTimeout(ajax_call, 500);
});
The php script should be able to update the database every time it gets called.

Categories