I am using Codeigniter and want to show progress of XML import.
but issue i am facing is
When view load, it stuck on loading (blank page) and when i can see view its shows 100% done.
my code as bellow
$i=0;
$count=sizeof($record->List);
foreach($record->List as $Item)
{
$i++;
echo "processing ".$i." of ".$count;
---processing code which takes times to process---
---processing code which takes times to process---
}
this code is in view but when i click on link to load this view, i have to wait for all process to complete and then i can see view when all process is done.
what i want is:
Show view (empty).
Then keep on printing each line as loop go.
Thanks
Here you got a example for progress bar using AJAX:
index.php
<?php
// Start the session.
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Progress Bar</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<style>
#progress {
width: 500px;
border: 1px solid #aaa;
height: 20px;
}
#progress .bar {
background-color: #ccc;
height: 20px;
}
</style>
</head>
<body>
<div id="progress"></div>
<div id="message"></div>
<script>
var timer;
// The function to refresh the progress bar.
function refreshProgress() {
// We use Ajax again to check the progress by calling the checker script.
// Also pass the session id to read the file because the file which storing the progress is placed in a file per session.
// If the call was success, display the progress bar.
$.ajax({
url: "checker.php?file=<?php echo session_id() ?>",
success:function(data){
$("#progress").html('<div class="bar" style="width:' + data.percent + '%"></div>');
$("#message").html(data.message);
// If the process is completed, we should stop the checking process.
if (data.percent == 100) {
window.clearInterval(timer);
timer = window.setInterval(completed, 1000);
}
}
});
}
function completed() {
$("#message").html("Completed");
window.clearInterval(timer);
}
// When the document is ready
$(document).ready(function(){
// Trigger the process in web server.
$.ajax({url: "process.php"});
// Refresh the progress bar every 1 second.
timer = window.setInterval(refreshProgress, 1000);
});
</script>
</body>
</html>
checker.php
<?php
// The file has JSON type.
header('Content-Type: application/json');
// Prepare the file name from the query string.
// Don't use session_start here. Otherwise this file will be only executed after the process.php execution is done.
$file = str_replace(".", "", $_GET['file']);
$file = "tmp/" . $file . ".txt";
// Make sure the file is exist.
if (file_exists($file)) {
// Get the content and echo it.
$text = file_get_contents($file);
echo $text;
// Convert to JSON to read the status.
$obj = json_decode($text);
// If the process is finished, delete the file.
if ($obj->percent == 100) {
unlink($file);
}
} else {
echo json_encode(array("percent" => null, "message" => null));
}
process.php
<?php
// Start the session.
session_start();
// The example total processes.
$total = 20;
// The array for storing the progress.
$arr_content = array();
// Loop through process
for ($i = 1; $i <= $total; $i++) {
// Calculate the percentation
$percent = intval($i / $total * 100);
// Put the progress percentage and message to array.
$arr_content['percent'] = $percent;
$arr_content['message'] = $i . " row(s) processed.";
// Write the progress into file and serialize the PHP array into JSON format.
// The file name is the session id.
file_put_contents("tmp/" . session_id() . ".txt", json_encode($arr_content));
// Sleep one second so we can see the delay
sleep(1);
}
Just that you write it on the CI and create a tmp folder, and you point a path to it in script. Good luck!
Related
I have a .php file that displays a .txt from my FTP server to a webpage.
My problem is that I want to get the .php page to refresh when something is added to the .txt file.
Right now I'm using this:
<?php
header("Refresh: 5; URL=$url1");
include('filename.txt');
?>
Which refreshes the page every five seconds to see if the .txt file is modified. I dislike this method because it spams my logs of who is viewing the webpage with the same information.
I was wondering if I could modify the .php to refresh only filename.txt is modified.
Use filetime() for this. http://php.net/manual/en/function.filemtime.php
Example from there
<?php
// outputs e.g. somefile.txt was last modified: December 29 2002 22:16:23.
$filename = 'somefile.txt';
if (file_exists($filename)) {
echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}
You can use a logic combination of PHP and Javascript (more specifically JQuery) with a trick. Of course this is a work-around approach (can be modified to make it better).
Pseudo-example can be like:
// A new PHP file "proxy.php"
<?php
if (!empty($_GET) && !empty($_GET['check'])) {
$previouslyChecked = $_GET['check'];
if (filemtime("filename.txt") > $previouslyChecked) {
echo 1;
} else {
echo 0;
}
die();
}
// Your PHP File
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
</head>
<body>
<?php
include('filename.txt');
$lastModified = filemtime("filename.txt");
?>
<input type="hidden" id="loadedAt" value="<?php echo $lastModified; ?>"/>
<script type="text/javascript">
function reloadPage(){
console.log("within reload");
window.location.reload();
}
function checkFile(){
console.log("checkfile");
jQuery.ajax({
type: "GET",
url: "proxy.php",
data: {check: jQuery("#loadedAt").val()},
success: function(data){
if (data == 1) {
console.log("reload called");
reloadPage();
}
setTimeout(checkFile, 5000);
}
});
};
jQuery(document).ready(function(){
console.log("checkfile called");
checkFile();
});
</script>
</body>
</html>
Hope this may work.
I have the following script:
function follow($file)
{
$currentSize = filesize($file);
$size = $currentSize;
$index=0;
while ($index<$currentSize) {
//echo "ENTERING LOOP!!!!";
clearstatcache();
$currentSize = filesize($file);
if ($size == $currentSize) {
usleep(100);
continue;
}
$fh = fopen($file, "r");
fseek($fh, $size);
while ($d = fgets($fh)) {
ob_end_flush();
echo $d;
ob_flush();
flush();
ob_start();
}
fclose($fh);
$size = $currentSize;
$index=$index+1;
}
}
follow("/var/www/devicemanagement/testFile.txt");
This script echoes a log file in real time and it works well when run in command line.
The following html code is meant to display the echoed lines from the php script:
<!DOCTYPE html>
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.js"></script>
<script>
var sentData = {
'param1': 'value1',
'param2': 'value2'
};
function successCallback(returnedData) {
$('#myDiv').html(returnedData);
}
function doAjaxCall() {
$.get('/labtool/controllers/tailor.php', sentData, successCallback);
//$.get('testFile.php', sentData, successCallback);
}
$(document).ready(function () {
var id;
$('#doStuff').click(function () {
clearInterval(id);
//$.get('testFile.php', sentData, successCallback);
});
id = setInterval(doAjaxCall, 1000);
});
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" id="doStuff">Change Content</button>
<div id="myDiv"></div>
</body>
</html>
I understand the key is using flush right, but despite my best efforts and a lot of experimenting I'm unable to get it to work.
Can anyone see what I'm doing wrong?
This works for me using info I gathered from probably many sources including stackoverflow, sorry about the formatting. Every time you have text to flush, simply call the function:
function flush_message($msg)
{
echo $msg;
// not a space, just '', I haven't tried removing it to see what happens
// cause I should really be working on something else right now!
echo str_pad('', 4096) . "\n";
ob_flush();
flush();
}
I also set
apache_setenv('no-gzip', 1);
ini_set('zlib.output_compression', 0);
at the beginning of script
Apparently there are lots of browser specific issues as well (regarding how big buffer until output is drawn) so you might want to test on different platforms to see how it performs.
I want to refresh two variables named profittext and sumtext which will be refreshed and echoed in the following places every few seconds. I know AJAX is needed to do this but how do i actually make it work ? The only way i found out was to refresh the content of the whole file. is there any way to refresh specific variables? Any answers will be greatly appreciated . Thank you very very much.
<table>
if($profitandloss<$zero) {
$profitText = "<div style=\"color: red;\">$profitandloss</div>";
} elseif ($profitandloss>$zero) {
$profitText = "<div style=\"color: green;\">$profitandloss</div>";
}
// for profit and loss counting
$sum+= $profitandloss;
//
echo "<tr><td>" . $row['trade_id'] .
"</td><td>" . $row['selection'] .
"</td><td>" . $row['date'] .
"</td><td>" . $row['type'] .
"</td><td>" . $row['size'] .
"</td><td>" . $row['bidprice'] .
"</td><td>" . $row['offerprice'] .
"</td><td>" . $row['stoploss'] .
"</td><td>" . $row['takeprofit'] .
"</td><td>" . $profitText .
"</td><td><a href ='delete.php?id=".
$row['trade_id']."'>X</a>
</td></tr>";
$profitandloss=0;
if($sum<$zero) {
$sumText = "<div style=\"color: red;\">$sum</div>";
} elseif ($sum>$zero) {
$sumText = "<div style=\"color: green;\">$sum</div>";
}
}
echo "</table><br>";
?>
<!DOCTYPE html>
<html>
<table style="border:1px solid black;">
<tr>
<th style="border:1px solid black;">Profit/Loss</th>
</tr>
<tr>
<td style="border:1px solid black;"><?php echo $sumText ;?></td>
</tr>
</table>
</html>
I struggled with the concept of how to structure such code when I first started too. Although it's not specific to your particular variables, here's a quick example for how to update a var through AJAX with jQuery/PHP.
Prologue: If this is something you're going to be doing often, you'll want to learn jQuery, rather than using normal javascript alone. There are lots of great, free, resources on how to learn jQuery. Alternatively, if you're not satisfied with the free tutorials online, this is an excellent book. I'll write the example in jQuery.
Design: Okay, so the way it works is this:
Set a timer in javascript to execute a particular function every X seconds (you DO NOT want to do it every second).
That function makes an AJAX call (with jQuery) to a .PHP file on the server, sending it the data necessary so that the .PHP code knows what to send back.
The .PHP code grabs the data required (e.g., with MySQL) encodes it in a JSON format, and exits.
A promise on the AJAX call is fired and the data sent from PHP is received. Process it as you will.
Repeat from step 2.
If you have any questions about what the code is doing, please ask.
AJAX.PHP
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$return_obj = array();
$request_obj = NULL;
// our AJAX call used "POST" as it's 'type', so we look in that
// variable.
if ( array_key_exists("func",$_POST) ) {
if ( $_POST['func'] === "get_update" ) {
if ( array_key_exists("which_var",$_POST) ) {
$which_var = $_POST['which_var'];
$which_var = $mysqli->real_escape_string($which_var); // should use prepared statements
// we sent 'num_people_logged_in' as our value here, so we'll be looking for a column/field
// with that value. this assumes that some other code, somewhere else,
// is regularly updating the table. it also assumes that there will only
// be a single row returned, which will hold the value.
$query = "SELECT '$which_var' FROM site_stats ";
if ( $result = $mysqli->query($query) ) {
if ( $row = $result->fetch_assoc() ) {
$request_obj[$which_var] = $row[$which_var];
}
}
}
}
}
$return_obj['request'] = $request_obj;
echo json_encode($return_obj);
die();
?>
MYCODE.JS
// this actually sends the AJAX request to the server.
function getUpdate() {
var jqXHR = $.ajax({
url : "ajax.php",
data : {
'func' : 'get_update',
'which_var' : 'num_people_logged_in'
},
dataType : 'json',
type : 'POST',
timeout : 10000
});
// attach 'promises' to the jqXHR object, which represents
// the AJAX call itself. 'promises' are, in this context,
// just events.
jqXHR.done(function(data,textStatus,jqXHR) {
// this executes if the AJAX call succeeded.
// the variable 'data' holds what the server
// sent us.
if ( ( data ) && ( data.request ) ) {
receiveUpdate(data.request);
}
});
jqXHR.fail(function(jqXHR,textStatus,errorThrown) {
// this executes if it failed
console.log("Fail: " + textStatus + " (" + errorThrown + ")");
});
jqXHR.always(function(a,textStatus,c){
// this executes either way, after .done or .fail
});
}
// this is called from jqXHR.done, on success
function receiveUpdate(request_obj) {
if ( request_obj.num_people_logged_in ) {
updateDOM(request_obj.num_people_logged_in);
}
}
function updateDOM(num_people_logged_in) {
if ( num_people_logged_in ) {
$("#mydiv > p.update").html("The updated value is: " + num_people_logged_in);
}
}
var timeoutID = null;
// setup our timer, to periodically make an
// AJAX call
function init() {
timeOutID = setInterval(function(){
getUpdate();
},5000);
}
// stop the timer
function cleanup() {
clearTimeout(timeoutID);
}
INDEX.HTML
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>AJAX practice</title>
<!-- <link href="mycss.css" rel='stylesheet'> if needed -->
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="mycode.js"></script>
<script>
$(document).ready(function() {
init();
$("#cleanup").on("click",function(){
cleanup();
});
}); // end ready
</script>
</head>
<body>
<div id='mydiv'>
<p>
How many people are online?
</p>
<p class='update'>
</p>
</div>
<button id='cleanup'>Stop updating!</button>
</div>
</body>
</html>
You will needd two PHP pages:
- one with HTML and JS, which periodicly makes ajax calls and puts the result to the HTML
- second with json (or even plain text) output of your dynamic data piece
Unfortunately, writing the full code in the answer is not someting that people do at stackoverflow, so just look at small example below, and try to figure out the missing parts.
http://jsfiddle.net/AMEqz/
var xhr = new XMLHttpRequest();
xhr.onload = function(r) {
// your render logic HERE
setTimeout(send, 1000);
}
function send() {
xhr.open("GET", "/", true);
xhr.send();
}
send();
p.s.: keep in mind that each ajax request will mean extra connection to your server, so make sure it can deal with the load ;)
Use a timer : https://developer.mozilla.org/en/docs/DOM/window.setInterval
setInterval(function(){
//update your var here
},1000);
Ok, Hopefully this makes a little sense. I have a changing amount of images within a folder which I use php to discover. The images that are found are then passed on to my javascript as variables for location and total number of files found in the given folder.
An array consisting of the various image locations is made and then used to create the new images that are appended to a already existing div.
The question would be how can I separate the appendChild part of the function so that it could be called after the full array had been built rather than appending every iteration. The hope in doing that would be to show a loading gif while the collection was being assembled and once that was to done append the array to the document as a whole instead of as each file is loaded.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
enter code here`<HTML>
<HEAD>
<TITLE>Use PHP in HTML files</TITLE>
<?php
$dir = "images/";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
$filecount = count($files);
}
uasort ( $files , function ($a, $b) {
return strnatcmp($a,$b); // or other function/code
}
);
print_r($files);
?>
<script language="javascript" type="text/javascript">
function map(id){
var photos = [];
var test = <?php echo json_encode($files); ?>;
var elements = <?php echo $filecount ?>;
for (i=0;i<=elements;i++){
photos[i] = new Array("images/" + test[i]);
image = new Image();
image.setAttribute("class", "container");
image.setAttribute("id", photos[i]);
image.src = photos[i];
image = document.getElementById("container").appendChild(image);
}
alert(elements);
}
</SCRIPT>
<style type="text/css">
.container {
position: absolute;
height: 664px;
width: 1024px;
left: 0;
top: 125px
}
#loadingBar {
position: absolute;
top: 30%;
left: 30%;
z-index: 100;
}
</style>
</HEAD>
<BODY>
<button id="lower_level" onclick="map(this)">Click This Confused Button</button>
<div id="container"></div>
</BODY>
</HTML>
Sorry for the hard to follow variable names. Feel free to chop up the code as much as you'd like. Just explain why things were changed! Also the php code is creating two elements that I don't understand "." and "..".
Elements "." and ".." means current and parent directories.
At the beginning of your function you can hide div:
document.getElementById("container").setAttribute("style","display:none");
and add yor loading gif.
After you function you hide your gif adn show div.
...
function map(id){
document.getElementById("container").setAttribute("style","display:none");
var photos = [];
var test = ;
var elements = ;
for (i=0;i<elements;i++){
if(test[i] '.' || test[i]'..')
continue;
photos[i] = new Array("../myProject/web/uploads/images/" + test[i]);
image = new Image();
image.setAttribute("class", "container");
image.setAttribute("id", photos[i]);
image.src = photos[i];
image = document.getElementById("container").appendChild(image);
}
alert(elements);
document.getElementById("container").setAttribute("style","display:block");
}
...
I have a comics website which loops through all images in a db and displays them as thumbnails.
The user can click on one of those images to see it in normal size on a viewComic.php template.
I'd like to allow users to press left and right arrows to navigate images.
So, my idea is:
pagination.php handles image display on correct pages (by offsetting) by looping through database result array. The user can click on a result (below) to go to that specific image on the viewcomic.php template.
'<br />IMG: <a href="./templates/viewcomic.php?id=' . $row['imgid'] . '&image=' . $imgpath.$row['imgname'] . '">
Now on viewcomic.php, I get the id and image, and display the image
$imgid = $_GET['id'];
$imgpath = $_GET['image'];
<center><img src=".<?php echo $imgpath ?>" /></center>
The user can press left and right arrows to navigate through images...
My goal was to somehow increment the image id to move to the next image, but that doesn't seem to be working...
<script type="text/javascript">
$(document).ready(function() {
$(document).keydown(function (e) {
if (e.which == 39) { //get next image
<?php
$count = 0;
$count++;
echo "<img src=" . $imageArray[$count] . "/>";
?>
}
});
});
</script>
Any ideas?
EDIT: I'm going to go through an image array passed in from pagination.php.
So, in my viewcomic.php file, I've updated my jquery script (see above).. but the jquery doesn't seem to like the embedded php, even though it's all in a php file.
Here's a picture of page source vs code:
Here is what i would do:
assuming that an imagepath is surrounded by quotes:
echo $imageArray[0]; // 'imagepath/image'
Script:
<script type="text/javascript">
var imgArray = [<?php echo implode(',',$imageArray) ?>];
// now the image array have the list of all your images.
$(document).ready(function() {
var img = document.getElementById("theImage");
imgIndex = 0;
$(document).keydown(function (e) {
if (e.which == 39) { //get next image
img.src = imgArray[imgIndex++]
}
... /* Logic to check if at the end of imageArray */ ...
});
});
</script>
The Html:
<center><img src="" id="theImage"/></center>
How about:
$(document).ready(function() {
$(document).keydown(function (e) {
if (e.which == 39) {
var nextId = $_GET['id'] + 1;
window.location = "./templates/viewcomic.php?id=" + nextId;
}
});
});
In this case your page is submit on every request, You can also handle this at client site.
Click link to see demo about rotate link using JavaScript. : Link Rotate using javascript