how to display a progress bar until my page loads? - php

I use php to fetch some information from database and I want to display a progress bar until my php executes and I need to display my page after the php execution. how can I achieve this.
Excatly like how the gmail loads the inbox

Have look at https://github.com/TheBrockEllis/jQuery-and-PHP-Progress-Bar
and also http://www.johnboy.com/blog/a-better-php-upload-progress-bar-using-jquery
It is fairly simple to do.

From the description I don't know how in depth this progress bar needs to be. This is pseudo code that should get you started. It won't run AS IS... you will need to make these functions do something.
EXAMPLE 1: 100% client side checker
<script type="text/javascript">
/* in document head */
var section1 = 0;
var section2 = 0;
var section3 = 0;
var section4 = 0;
//lightbox w/ progress meter
showProgressLightBox();
//async ajax calls here to load the various sectoins
loadPage(); // not a real function
function displayProgressMeter()
{
var count = 0;
if (section1) count++;
if (section2) count++;
if (section3) count++;
if (section4) count++;
if (count != 4) {
displayProgress(count); //will repaint lightbox progress meter
//based on X of Y sections loaded
setTimeout('displayProgressMeter()',500);
}
else
{
closeLightBox(); //page is loaded
}
}
displayProgressMeter(); //start the event
//note my ajax calls will flip the values of the various variables we are checking
</script>
Example 2 server checker. I have something like this running for a project that takes about 30 minutes to run a certain activity. The progress itself is updated by updating mysql from a cron scheduled task
First I have a PHP file called "batchStatusChecker" which looks something like this:
<?php
define('AREA',"COLREPORT");
include(__DIR__."/../phoenix/includes/config.php");
session_start();
$batch=(int)#$_REQUEST["batch"];
include (__DIR__."/affiliateUploadClass.php");
$rs=Query("select commitMessage from phx_AffiliateUsersFiles where ID=$batch;");
echo json_encode(array("info" => $rs->Get("commitMessage")));
?>
Then I have some javascript that updates a div with the current status or shows a completion message. You could adapt a technique like this to your needs if it is more appropriate for your use case
function checkStatusOfReport()
{
$.post("/affiliateUpload/batchStatusChecker.php", { "batch": <? echo $batch; ?> },
function(data)
{
if (data.error)
{
$("#ErrorInformation").html(data.error);
$("#UploadInformation").remove();
}
else
{
var msg="<h3>" + data.info + "</h3>";
$("#UploadInformation").html(msg);
if (data.info == 'COMPLETE')
$("#UploadInformation").html('<h3>The import of this batch is completed.</h3>');
else
setTimeout("checkStatusOfReport()",4000);
}
}, "json");
}
checkStatusOfReport();

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>Progress Bar</title>
</head>
<body>
<!-- Progress bar holder -->
<div id="progress" style="width:500px;border:1px solid #ccc;"></div>
<!-- Progress information -->
<div id="information" style="width"></div>
<?php
// Total processes
$total = 2;
// Loop through process
for($i=1; $i<=$total; $i++){
// Calculate the percentation
$percent = intval($i/$total * 100)."%";
// Javascript for updating the progress bar and information
echo '<script language="javascript">
document.getElementById("progress").innerHTML="<div style=\"width:'.$percent.';background-color:#ddd;\"> </div>";
document.getElementById("information").innerHTML="'.$i.' row(s) processed.";
</script>';
// This is for the buffer achieve the minimum size in order to flush data
echo str_repeat(' ',1024*64);
// Send output to browser immediately
flush();
// Sleep one second so we can see the delay
sleep(1);
}
// Tell user that the process is completed
echo '<script language="javascript">document.getElementById("information").innerHTML="Process completed"</script>';
?>
</body>
</html>

Related

PHP AJAX Comet with MySQL select record

I would like to implement comet with records fetch from PHP
My PHP will do the following.. at a page call getlog.php
$sql = "select log_description,log_time from log ORDER by log_time DESC";
$result=mysql_query($sql);
if($result == false)
{ die("unable to fetch records."); }
while ($row = mysql_fetch_assoc($result)) {
$result_output[] = $row;
}
$counter = 1;
foreach($result_output as $row)
{
echo $counter . ". " $row[log_description];
$counter++;
}
If there is new log, I would want to echo it out in viewlog.php
So it would appear like this in viewlog.php
1. Customer 1 logged in at 12:05.
maybe 5 minutes later
1. Customer 2 logged in at 12:10
2. Customer 1 logged in at 12:05
It maintain a maximum of like lets say 15 records.
The data is fetch from PHP, I read the way to do it is something call "comet" but I just want a simple database fetch which auto refresh e.g every 10 seconds to see if there is new record added to the database and append it to the div.
Is there a easy way to achieve this using AJAX and PHP and not using comet.
Thanks for all the help, greatly appreciate !
Did the following code changes
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
show_log(){
var lnk = "fetchlog.php";
$.ajax({url:lnk,success:function(result){
$("#log_div").html(result);
}});
}
window.setInterval(function(){
show_log();
}, 10000);
</script>
</head>
<body>
<div id="log_div"></div>
</body>
</html>
Whats wrong with my code as it doesn't fetch from fetchlog.php
fetchlog.php echo something like this
1. Acct_1 logged to the system.
2. Acct_3 logged in to the system.
3. Acct_2 logged in to the system.
4. Assign permissions on Acct_1.
5. Delete record on table building with id 80
jsFiddle
Yes you can use ajax for this and simply update a div in your html.
You need to have jquery linked in order to use the below code.
show_log(){
var lnk = "link to the viewlog.php file";
$.ajax({url:lnk,success:function(result){
$("#log_div").html(result);
}});
}
Run the show_log() function every x number of mins.
Have your viewlog.php show the last x number of records in the descending order of time.
You can update your sql to look like
$sql = "select log_description,log_time from log ORDER by log_time DESC LIMIT 5 ";
You can use the below inside your javascript to run the function every x number of seconds. In this every 10 seconds.
window.setInterval(function(){
show_log();
}, 10000);
the 10,000 is in miliseconds
----- Try the below
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
http = getHTTPObject();
function getHTTPObject(){
var xmlhttp;
if(!xmlhttp && typeof XMLHttpRequest != 'undefined'){
try {
xmlhttp = new XMLHttpRequest();
}catch(e){
xmlhttp = false;
}
}
return xmlhttp;
}
function show_log(){
var url = "viewlog.php";
http.open("GET", url, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function handleHttpResponse(){
if(http.readyState == 4){
document.getElementById('log_div').innerHTML = http.responseText;
}
}
setInterval ( "show_log()", 5000 );
</script>
</head>
<body>
<div id="log_div"></div>
</body>
</html>

Load page while PHP is executing

What Im trying to do: Display a loading gif or text... at the very least show a black screen before and during the time the php is being executed.
What I have tried.
I have tested using flush () and I get nothing until the entire php process is finished. I dont particularly like this concept either but I'll take anything.
I am considering using two pages to accomplish this though the current project is nearly complete and would take some time to consolidate the scattered html/php code.
Currently I'm doing 3-simpleXML_load_file(), 1-include(), 1-file_get_contents()
I have javascript function plotting data from one of the simpleXML_Load_file()...
Im up for moving parts of the code to a different file but it's a big task. So id like some advise or suggestions on how to proceed.
If I need to elaborate more just ask!
Thanks,
JT
<html>
<head>
<?php
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
$weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');
?>
<script type="text/javascript">
<!--Plot function-->
$(function()
{
var d =
[
<?php
//Pulling in hourly data to plot temp vs time
$i=0;
$array=array();
while ($i<=100)
{
echo '['. (strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000) .','.$weather_hourly->data->parameters->temperature->value[$i] .'],';
$value = $weather_hourly->data->parameters->temperature->value[$i];
array_push($array,$value);
$i++;
}
foreach ($array as $key => $value)
{
$value = (string) $value;
$min_sec_array[] = $value;
}
?>
</script>
</head>
<body>
<div id=graph>
</div>
</body
The main way you can accomplish this is by using AJAX and multiple pages. To accomplish this, the first page should not do any of the processing, just put the loading image here. Next, make an AJAX request, and once the request is finished, you can show the results on the page or redirect to a different page.
Example:
File 1 (jQuery must be included also), put this in the body along with the loader animation:
<script language="javascript" type="text/javascript">
$(function(){
var mydata = {};
$.post('/myajaxfile.php', mydata, function(resp){
// process response here or redirect page
}, 'json');
});
</script>
Update: Here is a more complete example based on your code. This has not been tested and needs to have the jQuery library included, but this should give you a good idea:
File 1: file1.html
</head>
<body>
<?php
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
?>
<!-- Include jQuery here! Also have the loading animation here. -->
<script type="text/javascript">
$(function(){
$.get('/file2.php?Lat=<?php echo $lat; ?>&Lon=<?php echo $long; ?>', null, function(resp){
// resp will have the data from file2.php
console.log(resp);
console.log(resp['min_sec_array']);
console.log(resp['main']);
// here is where you will setup the graph
// with the data loaded
<!--Plot function-->
}, 'json');
});
</script>
<div id=graph>
</div>
</body
</html>
File 2: file2.php
I'm not sure if you needed the $min_sec_array, but I had this example return that as well as the main data you were using before.
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
$weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');
//Pulling in hourly data to plot temp vs time
$i=0;
$main = array();
$array=array();
while ($i<=100)
{
$main[] = array((strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000), $weather_hourly->data->parameters->temperature->value[$i]);
$value = $weather_hourly->data->parameters->temperature->value[$i];
array_push($array,$value);
$i++;
}
foreach ($array as $key => $value)
{
$min_sec_array[] = (string) $value;
}
echo json_encode(array(
'min_sec_array' =>$min_sec_array,
'main' => $main
));
exit();
?>
I would recommend not to do this with plain html and php if u expect it modify the page after it is loaded. Because php is server side processing, so it is executed before the page is send to the user. U need Javascript. Using Javascript will enable u to dynamically add or remove html elements to or from the DOM tree after the page was send to the user. It is executed by the users browser.
For easier start I would recommend jQuery, because there are lots of tutorials on such topics.
JQuery
JQuery learning center
A small example:
HTML
<head>
<meta charset="utf-8" />
<title> </title>
<script type="text/javascript" src="js/lib/jquery-1.9.1.js"></script>
</head>
<body>
<h1>Addition</h1>
<div id="error_msg"> </div>
<div id="content">
<!-- show loading image when opening the page -->
<img src="images/loading.gif"/>
</div>
<script type="text/javascript">
// your script to load content from php goes here
</script>
</body>
this will be nothing more then the following until now:
adding the following php file
<?php
$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
$result = $num1 + $num2;
echo '<p>Calculating '.$num1.' + '.$num2.' took a lot of time, but finally we were able to evaluate it to '.$result.'.</p>'
.'<p> '.$num1.' + '.$num2.' = '.$result.'</p>';
?>
wont change anything of the html, but adding javascript/ Jquery inside the HTML will be kind of connection between static html and server side php.
$(document).ready(function(){
$.ajax({ // call php script
url: 'php/script.php?num1=258&num2=121',
type:'GET',
timeout: 500,
contentType: 'html'
}).success(function(data){
// remove loading image and add content received from php
$('div#content').html(data);
}).error(function(jqXHR, textStatus, errorThrown){
// in case something went wrong, show error
$('div#error_msg').append('Sorry, something went wrong: ' + textStatus + ' (' + errorThrown + ')');
});
});
This will change your page to show the loading animation until the php script returns its data, like:
So you can setup the whole page in plain html, add some loading gifs, call several php scripts and change the content without reloading the page itself.
It is kind of nasty solution to your problem...
But this can work:
You work with those -
ob_start();
//printing done here...
ob_end_flush();
at the beginning you will create your rotating ajax gif...
Then you do all the processing and calculating you want...
At the end of the processing, just echo a small script that does a hide to your gif...
Depends on the exact need, maybe ajax can be more elegant solution.
In response to your conversation with David Constantine below, did you try using ob_flush()?
ob_start();
echo '<img src="pics/loading.gif">';
ob_flush();
// Do your processing here
ob_end_flush();
I think you don't have a problem with flushing your PHP output to the browser, but more likely with getting the browser to start rendering the partial html output. Unfortunately, browser behavior on partial html is browser-specific, so if you want something to work the same in any browser, the AJAX solution suggested in other answers is the better way to go.
But if you don't like that added complexity of a full AJAX solution, you can try to make your html output "nice" in the sense of providing some body output that can be formatted without needing the rest of the html output. This is were your sample code fails: It spends most of its time outputting data into a script tag inside the html header. The browser never even sees the start of the body until your PHP code has practically finished executing. If you first write your complete body, then add the script tag for the data there, you give the browser something to at least try to render whilst waiting for the final script to be completed.
I've found the same issue (albeit not in PHP) discussed here: Stack Overflow question "When do browsers start to render partially transmitted HTML?" In particular, the accepted answer there provides a fairly minimal non-AJAX example to display and hide a placeholder whilst the html file hasn't completely loaded yet.
I know this is an old question, but the answer provided in this page by rpnew is extremely clear and easy to adjust to your project's requirements.
It is a combination of AJAX and PHP.
The HTML page PHPAjax.html which calls the PHP script:
<html>
<head>
<script type="text/javascript">
document.write('<div id="loading">Loading...</div>');
//Ajax Function
function getHTTPObject()
{
var xmlhttp;
if (window.ActiveXObject)
{
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E)
{
xmlhttp = false;
}
}
}
else
{
xmlhttp = false;
}
if (window.XMLHttpRequest)
{
try
{
xmlhttp = new XMLHttpRequest();
}
catch (e)
{
xmlhttp = false;
}
}
return xmlhttp;
}
//HTTP Objects..
var http = getHTTPObject();
//Function which we are calling...
function AjaxFunction()
{
url='PHPScript.php';
http.open("GET",url, true);
http.onreadystatechange = function()
{
if (http.readyState == 4)
{
//Change the text when result comes.....
document.getElementById("content").innerHTML="http. responseText";
}
}
http.send(null);
}
</script>
</head>
<body onload="AjaxFunction()">
</body>
</html>
The Background PHP Script PHPScript.php:
<?php
sleep(10);
echo "I'm from PHP Script";
?>
Save both files in the same directory. From your browser open the HTML file. It will show 'Loading...' for 10 seconds and then you will see the message changing to "I'm from PHP Script".

Write to div as data streams in

Consider an AJAX call that writes to a div:
recent_req=$.post('result.php', { d: data }, function(returnData) {
$('#content').html(returnData);
});
The PHP script at result.php performs some functions that take time, about 5-20 seconds per step. I am using PHP's flush() function to get the info to the browser as soon as each step starts and ends, but how can I get the Javascript to write the data to the #content div as it comes in?
Thanks.
EDIT:
To clarify: Assume result.php looks like the following and due to constraints cannot be practically refactored:
<?php
echo "Starting...<br />";
flush();
longOperation();
echo "Done with first long operation.<br />";
flush();
anotherLongOperation();
echo "Done with another long operation.<br />";
flush();
?>
How might the AJAX be structured to call result.php such that the echo statements are appended to the #content div as they come in? Any solution with / without jQuery is welcome. Thanks!
There's a technique using an iframe which you could use to achieve this.
Similar to other suggestions involving frames but it doesn't involve sessions or polling or anything, and doesn't need you to display the iframe itself. It also has the benefit of running any code you want at any point in the process, in case you're doing something more sophisticated with your UI than just pushing text to a div (e.g. you could update a progress bar).
Basically, submit the form to a hidden iFrame then flush javascript to that frame, which interacts with functions in the iFrame's parent.
Like this:
HTML:
<form target="results" action="result.php" method="post">
<!-- your form -->
<input type="submit" value="Go" />
</form>
<iframe name="results" id="results" width="0" height="0" />
<div id="progress"></div>
Javascript, in your main page:
function updateProgress(progress) {
$("#progress").append("<div>" + progress + "</div>");
}
result.php:
<?php
echo "<script language='javascript'>parent.updateProgress('Starting...');</script>";
flush();
longOperation();
echo "<script language='javascript'>parent.updateProgress('Done with first long operation.');</script>";
flush();
anotherLongOperation();
echo "<script language='javascript'>parent.updateProgress('Done with another long operation.');</script>";
flush();
?>
You cannot 'stream' data using regular ajax calls, for you can't make your user's browser 'listen' to server requests. Your 'success' function will only be called when data's done processing.
There's, though, much discussion on 'Ajax Push' on the internet and apparently HTML5 has websocket objects that can be used to make your user's browser listen to server requests. The syntax definition is not quite stable yet, so you don't want to mess with it, as it may change soon.
What you may want to do is dispatch a request for step1, wait for its return and then dispatch a request for step2. It'll add some overhead to your overall processing time (and will make it much more verbose), but it should work fine if you only have a few big steps. If your steps don't take too much processing, you shouldn't do it (as the communication time will become greater than your 'effective processing time').
EDIT: What you can also do is write the progress on the user's session, for example. That way, you can periodically ping the server with a request for an update on the status. This way, even if you have many small steps, you'll only have to dispatch requests every 10 seconds or so, that being an improvement over dispatching for every step.
As an alternative solution, you could submit a hidden form into an iframe, as shown in the following example:
<?php
function output_data($data) {
echo str_pad($data, 4096, ' ', STR_PAD_RIGHT) . "\n";
flush();
}
function long_runner() {
output_data("");
output_data(date("H:i:s").' - Starting...<br />');
sleep(10);
output_data(date("H:i:s").' - Done with first long operation.<br />');
sleep(10);
output_data(date("H:i:s").' - Done with another long operation.<br />');
return("<script>parent.task_complete()</script>");
}
if (isset($_REQUEST["status"])) {
die(long_runner());
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Write to IFRAME as data streams in</title>
<style>
#myform { display: none }
#frm { width: 50% }
</style>
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function task_complete() {
alert('Task completed');
}
$(document).ready(function() {
$('#starter').click(function() {
$('#myform').submit();
});
});
</script>
</head>
<body>
<form id="myform" method="get" target="frm" action="<?= $_SERVER['SCRIPT_NAME'] ?>">
<input type="hidden" name="status" value="0">
</form>
Start<br />
<iframe id="frm" name="frm" frameborder="0"></iframe>
</body>
</html>
Writing a dynamic data stream to a div:
Here goes.. you asked specifically how to dynamically write data streams to a "div". As many have said it is possible to write dynamically to an iframe and we just need to go one step further. Here is a complete solution to your issue, which will bring that data back to your div with a maximum delay of .5 seconds. It can be adapted if you need a more prompt update.
<!DOCTYPE html>
<html>
<head>
<title>dynamic listener</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
var count;
$(function(){
$('#formx').submit(function(){
setTimeout(function(){ check_div(); }, 500);
count = 0;
return true;
});
});
function check_div()
{
var $iframetxt = $('#iframex').contents().text();
var $div = $('#dynamic');
if( $iframetxt != $div.text() )
{
console.log('rewritten!');
$div.text( $iframetxt );
setTimeout(function(){ check_div(); }, 500);
count = 0;
}
else
{
count++;
if(count < 40) setTimeout(function(){ check_div(); }, 500);
else console.log('timed out');
}
}
</script>
</head>
<body>
<div>
Form
<form id="formx" action="result.php" method="post" target="iframex">
<input type="submit" />
</form>
</div>
<div id="dynamic"></div>
<iframe id='iframex' name="iframex" style="display:none" ></iframe>
</body>
</html>
1. On form submit, the streaming data is sent to the iframe.
For this we just set the target attribute in the form tag to the iframe name.
2. check_div() runs every .5 seconds to compare the text of #dynamic div to the text contents of the iframe.
If there is a difference between them, the data is written to the div and the timeout is called again. If there is no difference, the timeout counter increments. If the count is less than 40 (40 x .5 sec = 20 seconds), it calls the timeout again. If not, we assume the stream has completed.
Here is a solution using polling with a session:
HTML:
<!DOCTYPE html>
<html>
<body>
<div id="content"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var pollTimeout;
function pollResult(){
$.get('poll.php', function(response) {
// Update #content with partial response
$('#content').html(response);
pollTimeout = setTimeout(pollResult, 1000);
});
}
$.post('result.php', function(response) {
// Result is loaded, stop polling and update content with final response
clearTimeout(pollTimeout);
$('#content').html(response);
});
// Start polling
pollResult();
</script>
</body>
</html>
Result PHP:
<?php
class SemiStream{
public function __construct(){
#session_start();
$_SESSION['semi_stream'] = '';
}
public function write($data){
#session_start();
$_SESSION['semi_stream'] .= $data;
// We have to save and close the session to be
// able to read the contents of it in poll.php
session_write_close();
}
public function close(){
echo $_SESSION['semi_stream'];
unset($_SESSION['semi_stream']);
}
}
$stream = new SemiStream();
$stream->write("Starting...<br />");
sleep(3);
$stream->write("Done with first long operation.<br />");
sleep(3);
$stream->write("Done with another long operation.<br />");
$stream->close();
echo 'Done.';
Poll PHP:
<?php
session_start();
echo $_SESSION['semi_stream'];
This works, without the use of PHP's output buffering.
Check out the Pusher service, seems like it could do exactly what you want: http://pusher.com/
Probably, the question is about how to implement Push technology in your app. I would suggest you to look this question which has great answer with example

autorepeat a php script

i would like to ask how can i make a php script which echoes the id of the data stored in a database repeat itself after specific time for example after 2 minutes.i don't want to use a cron job or another scheduler.Just php or javascript implemantation.Thanks in advance..
I've done similar with this script. While the user is on the page, it runs scriptToRun.php every 2 minutes.
function changeFeedAddress() {
$.ajax({
type: 'get',
url: 'scriptToRun.php',
success: function(txt) {
// do something with the new RSS feed ID here
}
});
}
setInterval(changeFeedAddress,120000); // 2 MINUTES
Alternate to #JMC Creative (Self-contained for example's sake):
<?php
// check if the $.post below is calling this script
if (isset($_POST['ajax']))
{
// $data = /*Retrieve the id in the database*/;
// ---vvvv---remove---vvvv---
// Example Data for test purposes
$data = rand(1,9999);
// End Example Data
// ---^^^^---remove---^^^^---
// output the new ID to the page so the $.post can see it
echo $data;
exit; // and stop processing
}
?>
<html>
<head>
<title>Demo Update</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
// assign a timeout for this script
var timeout = 2 * 60000; // 2 minutes
// create a function we can call over and over to fetch the ID
function updateDBValue(){
// call this same script and retrieve an "id from the database" (see top of page)
$.post('<?php echo $_SERVER['PHP_SELF']; ?>',{ajax:true},function(data){
// 'data' now contains the new ID. For example's sake, place the value
// in to an input field (as shown below)
$('#db-value').val(data);
// set a timer to re-call this function again
setTimeout(updateDBValue,timeout);
});
}
// call the function initially
updateDBValue();
});
</script>
</head>
<body style="text-align:center;">
<div style="margin: 0 auto;border:1px solid #000;display:block;width:150px;height:50px;">
DB Value:<br />
<input type="text" id="db-value" style="text-align:center;" />
</div>
</body>
</head>
Why not just do this?
<?php
header('refresh: 600; url=http://www.yourhost.com/yourscript.php');
//script here
?>
If your generating your ID at random from within the script...this will work fine. The page will refresh itself every 10 minutes.

how to return multiple array items using json/jquery

Hey guys, quick question, I have a query that will usually return multiple results from a database, while I know how to return one result, I am not sure how to return multiple in jquery. I just want to take each of the returned results and run them through my prepare function. I have been trying to use 'for' to handle the array of data but I don't think it can work since I am returning different array values. If anyone has any suggestions, I would really appreciate it.
JQUERY RETRIEVAL
success: function(json) {
for(i=0; i < json.rows; i++) {
$('#users_online').append(online_users(json[i]));
$('#online_list-' + count2).fadeIn(1500);
}
}
PHP PROCESSING
$qryuserscount1="SELECT active_users.username,COUNT(scrusersonline.id) AS rows FROM scrusersonline LEFT JOIN active_users ON scrusersonline.id=active_users.id WHERE topic_id='$topic_id'";
$userscount1=mysql_query($qryuserscount1);
while ($row = mysql_fetch_array($userscount1)) {
$onlineuser= $row['username'];
$rows=$row['rows'];
if ($username==$onlineuser){
$str2= "<div class=\"me\">$onlineuser</div>";
}
else {
$str2= "<b><div class=\"others\">$onlineuser</div></b>";
}
$data['rows']=$rows;
$data['entry']=$str1.$str2;
}
EDIT ONLINE USERS FUNCTION
function online_users(response) {
count2++;
var string = '<div class="update-entry"><li id="online_list-'+count2+'">'
+ ''+response.entry+''
+'</li></div>';
return string;
}
Hopefully this will help you get pointed in the right direction:
foo.php
<html>
<head>
<script type="text/javascript" src="user_list.js"></script>
<style type="text/css" media="screen">
/* instead of using html tags for markup, use CSS */
#users_online .me {}
#users_online .other { font-weight: bold; }
</style>
</head>
<body>
<div id="content">foo</div>
<div id="users_online">
<div class="count"></div>
<div class="list"></div>
</div>
</body>
</html>
user_list.js
<script type="text/javascript" charset="utf-8">
(function($){
var refresh_user_list = function(){
// get the data
$.getJSON("/user_list.php", function(data)){
// insert HTML into DOM
$("#users_online .count").html(data['count']);
$("#users_online .list").html(data['users']);
};
// refresh users list again every 15 seconds
setTimeout(refresh_user_list, 15000);
};
// after the page is ready, get the user list
$(document).ready(function(){
refresh_user_list();
});
})(jQuery);
</script>
user_list.php
<?php
// header
header("Content-Type: application/json");
// return data
$data = array(
"users" => "",
"count" => 0
);
// query users
$result = mysql_query("
SELECT
active_users.username,
COUNT(scrusersonline.id) AS rows
FROM scrusersonline
LEFT JOIN active_users ON scrusersonline.id=active_users.id
WHERE topic_id='$topic_id';
");
// load users
while($u = mysql_fetch_object($result)){
$link_class = ($username == $u->username)
? "me"
: "other"
;
// don't use <b> tag here. define bold in the stylesheet with the link's class
$data["users"] .= "<a class=\"${link_class}\" href=\"statistics.php?user={$u->username}\">{$u->username}</a>";
}
// load count
// this is sort of silly, but I don't know the way your database is setup so it's hard to advise you how to improve it
$data["count"] = $u->rows;
// return the result
echo json_encode($data);
// make sure you stop the script here so nothing else gets output
exit;
?>
Why do you need to return multiple results? For something as simple as that, just format everything on the server-side and return all the HTML at once, then have jQuery just put it in. Don't make the client-side have to process things because it will likely be slower.

Categories