How to show processing ajax send? - php

My function have for loop and once loop it's output percent of that loop. It's look like this:
function checkisset($v){
foreach ($variable as $key=>$value)
if($v==$value) echo $key/count($variable);
}
and in client i want to show process of loop.
Ex: count($varibale)=10; First time in loop it will be 10%; and when 100% will run success function.
How can i do it??
Tks everyone.

To update your webpage dynamically, you have to establish communication between the client and the server, and send updates.
One way to send updates is "Server sent events". Another is "forever frame", where the page opens javascript link to the server and the server sends javascript statements over time.
In either case, you loop with updates will be a separate resource from the main page that you intend to update.

Related

show output of loops in realtime

I have a php script which is something like below.
script.php
<?php
foreach($available as $loop)
{
echo file_get_contents($loop);
}
?>
basically loop runs like 100 to 200.When I run domain.com/script.php on browser..output is displayed only after all the loop is completed.But I want the page to update the output in realtime.
Is it posible by setting some kinda of header in php script or via htacces ?
You can do this with some servers using the flush() function.
You may be better off using JavaScript and AJAX to fetch and display progress of your long-running task, though.

how to display info in Firebug using Firephp

I am trying to display some info from a ajax call using firephp and firebug.I am able to display someinfo when the ajax call is done. Is there a way to display while it is executing? For example my code below id inside a foreach loop.
foreach ($this->PreQualcalls as $value) {
ob_start();
if(isset($array ['env:Envelope'] ['env:Body']['n1:preQualResponse1207'])){
$this->setKeyNamePreQualResponse("n1:preQualResponse1207");
$this->setKeyNameServiceProducts("n1:ServiceProduct1207");
$this->setKeyNameModemProducts("n1:ModemProduct1207");
$this->firephp->log("entered the 1207 call");
}else{
$this->setKeyNamePreQualResponse("n1:preQual1308Response");
$this->setKeyNameServiceProducts("n1:ServiceProduct1308");
$this->setKeyNameModemProducts("n1:ModemProduct1308");
$this->firephp->log("entered the 1308 call");
}
ob_flush();
$this->firephp->log($this->getKeyNamePreQualResponse(),"Response type");
}
i want to be able to display getKeyNamePreQualResponse() in the console as it is being going through the loop.
Is it possible?
thank you.
FirePHP is designed to collect log information while the PHP script executes and then sends it in special headers along with the page response. It will not show logging calls in Firebug in realtime.
To debug your code using logging, place more logging calls into the loop. e.g.
$this->firephp->log("value", $value);
You have a loop that assigns a new value to $value on each iteration but don't use it in any of the statements in the loop. That does not seem right.
If you need realtime debugging I suggest using xDebug or other realtime logging tool.

Progress Bar when running function inside foreach loop

I have a foreach loop that calls a function to set values to an array. Sometimes it takes hours to complete depending on how many times it has to run thru the function to complete.
What I would like to have is a progress bar or at least a 1/1000 completed type progress indicator.
Is this possible? If so how could I implement this into my code? Would it be in the function or in the foreach loop? Been researching and found some examples using for and $i++ but I am not really sure how to implement that since I am already using a foreach loop.
Thanks much.
function scrape_amazon($links) {
//my code runs here to set all values in $ret array.
}
foreach($links as $link) {
$ret = scrape_amazon($link);
}
PHP probably isn't really the right tool for this task, however what you could do is:
Launch the slow code as a background process, and output progress to a file.
Have a PHP script that polls that file for progress information (either by page refresh or AJAX)
Launching the background process can be done in several ways, including:
Launch via cron every 60 seconds, and poll for new jobs spooled in some readable area
Launch via a fork/exec mechanism from a web page
Launch as a daemon at system startup
It will take some effort to avoid problems with multiple executions and/or overlap.
I use this, which well, not an ajax, do only flushing, but not so ugly.
I place an image
<img src='progress.gif' height=18 width=0 name=probar>
Then set on every event done on server a echo a line, then flush:
echo "<script language='JavaScript'>\ndocument.probar.width=".(($sys["probar_width"]/$task_all)*$task_i).";\n</script>\n";
flush();
If your server (eg. apache) use caching (eg. gzip is enabled) it won't work well.

How to design an AJAX interface to show progress bar based ona running script backend

Ok here is my problem.
I have a file which outputs an XML based on an input X
I have another file which calls the above(1) file with 10000 (i mean many) times with different numbers for X
When an user clicks "Go" It should go through all those 10000 Xs and simultaneously show him a progress of how many are done. (hmm may be updated once every 10sec).
How do i do it? I need ideas. I know how to AJAX and stuff, but whats the structure my program should take?
EDIT
So according to the answer given below i did store my output in a session variable. It then outputs the answer. What is happening is:
When i execute a loong script. It gets executed say within 1min. But in the mean time if i open (in a new window) just the file which outputs my SESSION variable, then it doesnt output will the first script has run. Which is completely opposite to what i want. Whats the problem here? Is it my syste/server which doesnt handle multiple requests or what?
EDIT 2
I use the files approach:
To read what i want
> <?php include_once '../includeTop.php'; echo
> util::readFromLog("../../Files/progressData.tmp"); ?>
and in another script
$processed ++;
util::writeToLog($dir.'/progressData.tmp', "Files processed: $processed");
where the functions are:
public static function writeToLog($file,$data) {
$f = fopen($file,"w");
fwrite($f, $data);
fclose($f);
}
public static function readFromLog($file) {
return file_get_contents($file);
}
But still the same problem persist :(. I can manually see the file gettin updated like 1, 2, 3 etc. But when i run my script to do from php it just waits till my original script is output.
EDIT 3
Ok i finally found the solution. Instead of seeking the output from the php file i directly goto the log now and seek it.
Put the progress (i.e. how far are you into the 2nd file) into a memcached directly from the background job, then deliver that value if requested by the javascript application (triggered by a timer, as long as you did not reach a 100%). The only thing you need to figure out is how to pass some sort of "transaction ID" to both the background job and the javascript side, so they access the same key in memcached.
Edit: I was wrong about $_SESSION. It doesn't update asynchronously, i.e. the values you store in it are not accessible until the script has finished. Whoops.
So the progress needs to be stored in something that does update asynchronously: Memory (like pyroscope suggests, and which is still the best solution), a file, or the database.
In other words, instead of using $_SESSION to store the value, it should be stored by memcached, in a file or in the database.
I.e. using the database
$progress = 0;
mysql_query("INSERT INTO `progress` (`id`, `progress`) VALUES ($uid, $progress)");
# loop starts
# processing...
$progress += $some_increment;
mysql_query("UPDATE `progress` SET `progress`=$progress WHERE `id`=$uid");
# loop ends
Or using a file
$progress = 0;
file_put_contents("/path/to/progress_files/$uid", $progress);
# loop starts
# processing...
$progress += $some_increment;
file_put_contents("/path/to/progress_files/$uid", $progress);
# loop ends
And then read the file/select from the database, when requesting progress via ajax. But it's not a pretty solution compared to memcached.
Also, remember to remove the file/database row once it's all done.
You could put the progress in a $_SESSION variable (you'll need a unique name for it), and update it while the process runs. Meanwhile your ajax request simply gets that variable at a specific interval
function heavy_process($input, $uid) {
$_SESSION[$uid] = 0;
# loop begins
# processing...
$_SESSION[$uid] += $some_increment;
# loop ends
}
Then have a url that simply spits out the $_SESSION[$uid] value when it's requested via ajax. Then use the returned value to update the progress bar. Use something like sha1(microtime()) to create the $uid
Edit: pyroscope's solution is technically better, but if you don't have a server with memcached or the ability to run background processes, you can use $_SESSION instead

Using Jquery to update a page when a database is modified

I want to update a page when my database is modified. I want to use jquery for doing this. Question not clear? Then have a look at this, Suppose this is my page:
<?php
$query=mysql_query("select * from tbl1 where user='admin'");
if(mysql_num_rows?($query)!=0)
{
echo 'Table 1 has values';
} else {
echo 'Table1 is empty';
}
?>
This action should be performed whenever any new entry is added to the database. Now suppose I add an entry to the database manually then the page should automatically show the result as "Table1 has values". I know it can be used by using refresh page periodically but I don't want to use it. Instead I want to try something other, like ajax polling? Can someone give me a demo?
You can use long polling, but do a lot of research first. Your server may kill the request that appears to be open for a long amount of time.
In PHP, your code will look something like...
set_time_limit(0);
while (TRUE) {
// Query database here
if ($results) {
echo json_encode($results);
exit;
}
sleep(1);
}
You can use Ajax jQuery Framework with Ajax:
http://www.w3schools.com/Ajax/default.asp
http://api.jquery.com/jQuery.ajax/
It will call the server side script Asynchronously and update your page accordingly. You can use jQuery to specify the format of the update also.
You are looking for Ajax-Push/Comet solutions. These aren't trivial.
You also mentioned ajax pooling.
Well, on the server side you need to loop until you have a timeout (that you defined yourself or the server did, make sure you return the HTTP status code for Timeout Occured) or the request can be satisfied.
And on the client side whenever you complete the operation successfully just handle it and than make the same ajax call again, if you timed out just make the same ajax request again until it's satisfied.

Categories