Can we make an incremental counter with only PHP? - php

I would like to know if it's possible without javascript to update an echo ?
For example
<?php
for ($i = 1; $i < 100; $i++){
echo $i;
}
?>
But it will only update the number without adding another line, and another until 100. Is this possible or only with javascript you can achieve this.
I need to output a counter to know how much files is being processed at the moment like
45 of 100 pages

No. client side (JavaScript for example) only. Because if you want to achieve this without page reload, then how PHP could be involved if PHP starts when request from browser comes?

PHP is a server-side language. The script is requested, executed and then sent to the client.
JavaScript executes client-side only. Which means that it can send a request to a PHP script, but will always return the result of the script.
The only option is AJAX requests. Basically, you write a PHP script that moves one file at a time. JavaScript handles the loop from 1 to 100 and send 100 synchronous requests to the PHP script with different parameters. Then you can track the progress and update DOM elements on your HTML page.
jQuery has a nice .ajax() function that can get you started. Below is a quick example. It won't work right off the bat but you can build on it to make it work.
PHP
<?php
$file = $_POST['file'];
$destination = $_POST['destination'];
// Move the stuff!
?>
JavaScript
var files = ['test.txt', 'test2.txt' /* ... */], /* Your list of files... */
destination = '/path/to/send/to/the/php/script/';
for(var i = 0; i < files.length; i ++){
$.ajax({
async: false,
url: 'script_to_move_files.php',
data: { file: files[i], destination: destination },
success: function(){
/* File moved! Update a progress bar or something... */
},
error: function(){
/* File wasn't moved successfully... */
}
});
}

Related

Show PHP process in a DIV without having to wait to finish via JQUERY

I have two scripts
I want to send via jQUERY a form to a PHP file, and see in a DIV the process, but it waits until if finish to show all, and sometimes it can take a few seconds making the user thinks its not doing anything
Here is what I have
I have a form like this
<button type="button" id="agregarfotos"> Load</button>
<div id="respuesta" style="width: 100%"></div>
<script>
$(document).ready(function() {
$('#agregarfotos').click(function() {
$.ajax({
type: 'post',
url: '../clases/class-album-procesar.php',
data: $('#mainforma').serialize(),
success: function (response) {
$('#respuesta').html(response);
});
});
});
</script>
And a PHP file named class-album-procesar.php with this:
<?php
ob_implicit_flush(1);
for($i=0; $i<15; $i++){
echo $i;
//this is for the buffer achieve the minimum size in order to flush data
echo str_repeat(' ',1024*64);
sleep(1);
}
?>
If I run the class-album-procesar.php file by it self, I can see the numbers 1 to 14 one by one, like it should, but if I run it via the jquery file, it waits until the page is completed loaded to show the result
Is there a way to do this without having to wait until it finish?
Instead of doing the loop in php do it on jQuery.
for(var i = 0; i < 15; i++) {
$.ajax({..});
}
This way you will be splitting the processing on multiple php processes, so instead of one long php script you have multiple short php scripts
I think you need to use third party jQuery library, but not sure that work fine.
Because, During ajax call PHP server busy with process. At that time server can't send any data to client. Server wait for finish that process and send data or information to client with request status 200.

Ajax multiple echos from PHP

Say, I have a php file like this:
<?php
echo 1;
//some functions
echo 2;
//more code to execute
echo 3;
?>
And I have an html form. So what I want in this form is to print echos in some textfield while PHP script is being executed, is it possible with AJAX and JQuery?
What I want is that user enters HTML page, presses some button, this button runs PHP script and every time script reaches echo he can see this echo in textfield. Once script is over - I want to do some JQuery action, like hide button, for example. Is it possible? What would an overview algorithm be? Thanks!
UPDATE:
I need to run this script ONCE when user presses button, but update textfield every time script reaches next echo, so that user presses button once, than he will see "1" in textfield, in a second he will see "2", in few more seconds - "3".
Unfortunately, since the success handler of .ajax() will only be called once the request has finished, you can't do a "live update".. :(
All you can really do is save your current state in a session, end your script at each echo and re-request the page to continue.
You can use two ways either return the response as json
$values = array();
$values['first'] => 1;
$values['second'] => 2;
$values['third'] => 3;
print json_encode($values);
and in the client side jquery success handler
$.ajax({
url: 'yoururl',
type:'POST',
data :'{ if any }'
dataType:'json', /*most important**/
success:function(data){
console.log(data.first); //first value..etc
}
});
second method
Append the return data on the server side
$return= '';
$return.=1."||";
$return.=2."||";
$return.=3;
echo $return;exit;
and in the ajax
$.ajax({
url: 'yoururl',
type:'POST',
data :'{ if any }'
success:function(data){
console.log(data.split("||")[0]); //first value..etc
}
});
});
You could return a JSON-string that PHP creates for your:
$values = array();
$values['first'] => 1;
$values['second'] => 2;
$values['third'] => 3;
print json_encode( values );
Than store this response in a JavaScript variable and use the values of it to update at the specific time:
var obj = jQuery.parseJSON( response );
// as an example - to see where this goes
setTimeout(function() { $('#example').html(obj.first); }, 1000);
More information:
PHP json_encode
jQuery jQuery.parseJSON((
Another solution by using two php scripts:
first is your actual one, which will store out data in session instead of echoing them
second script will just echo data stored in the session
Your client in javascript, will call the first script to launch the main job. Then call the second script to check and show advancement.
The second script which checks the session can be written in two ways:
only check and directly return, with or without new data (you call it every second by example)
return directly if there is data, else just wait for data (or a timeout), and when the script returns you just recall him
The second solution is closer to "realtime" and will do much fewer ajax calls.
An option is to use WebSockets, it will allow "real time" communication between your PHP and Javascript.
Native WebSockets are only supported by newer versions of modern browsers, but there is some method for old browsher to emulate this, using ajax/iframe/flash
by exemple, the socket.io client can work with internet explorer 5.5.
I had one such requirement. I noticed that though jquery's ajax ie. using $.ajax does not allow it. But using ajax without jquery does accept multiple echoes from php.
var ajax = new XMLHttpRequest();
ajax.open("POST", url, true);
ajax.send();
ajax.onreadystatechange = function ( )
{
if (this.readyState == 4 && this.status == 200)
{
console.log(this.responseText)
}
};

Image wont change

I am trying to get the image links from 9gag (what also works) and when I click on a button the image changes to the next one. The basic problem is that it works only once. I can then switch between the 1st and the 2nd image, though. This should be pretty simple, but I ´ve got no clue where the error is, so thanks in advance to anyone bothering to look at this.
<?php
$index = 0
$html = file_get_contents("http://www.9gag.com");
preg_match_all( '|http://d24w6bsrhbeh9d\.cloudfront\.net/photo/.+?\.jpg|', $html, $gags);
?>
<script>
function nextImg(){
<?php $index++;?>
pic.src='<?php echo $gags[0][$index];?>';
}
function prevImg(){
<?php $index--;?>
pic.src='<?php echo $gags[0][$index];?>';
}
</script>
You can't increment your PHP variables after the page has loaded. You are trying to increment them client-side with JavaScript. You are going to need to call that PHP using AJAX if you want to do this without refreshing the page, and even then you'll want to increment a javascript variable to keep track of where you are.
EDIT: I went a little nuts creating an ajax routine using PHP and JavaScript, specifically the jQuery library, which you will need to link to for this to work. You may also need to modify parts of the script to work with what you're trying to accomplish, but this certainly is a guide for running your ajax app as you're hoping to.
Start by making a PHP file with this script:
<?php
// Set content header to json
header('Content-Type: application/json');
// Get the index from the AJAX
$index = $_GET['index'];
// Grab file contents & parse
$html = file_get_contents("http://www.9gag.com");
preg_match_all( '|http://d24w6bsrhbeh9d\.cloudfront\.net/photo/.+?\.jpg|', $html, $gags);
// Send filename back to AJAX script as JSON
echo json_encode(array($gags[0][$index]));
?>
Then, in your HTML, include this jQuery to complete AJAX calls to your PHP script, and update the DOM with the data from the PHP script.
<script>
$(function() {
'use strict';
// Initiate index variable
var index = 0;
// Load initial image
loadImage(index);
// Add click event to a button with class of next-btn
$('.next-btn').click(function(e) {
e.preventDefault();
// Increment index to get next image
index++;
// Run AJAX function to retrieve image
loadImage(index);
});
// Add click event to a button with class prev-btn
$('.prev-btn').click(function(e) {
e.preventDefault();
// Decrement the index if it isn't 0
if (index > 0) {
index--;
}
// Run AJAX function to retrieve image
loadImage(index);
});
});
function loadImage(index) {
'use strict';
$.ajax({
type: 'GET',
url: 'your-php-script.php', // Filepath to your PHP script
data: 'index='+index, // Index is passed through GET request
dataType: 'json', // Return JSON
success: function (data) { // If the php script succeeds
// Change img with class of pic's src
// to the filename retrieved from php
$('.pic').attr('src', data[0]);
}
});
}
</script>
Configuring this for your needs will require some serious PHP and jQuery/JavaScript knowledge, as some debugging will likely be needed. Good luck!
EDIT 2:
I uploaded the working (tested, it works) source files to my website if you want to download. Please accept answer and let me know you grabbed the files...
http://www.wedgewebdesign.com/files/ajax-image-loader.zip
#Eric basically has it right but didn't really go into detail if you aren't familiar with the model...
PHP is a server side language in that it does all its processing on the web host server and once it is complete sends a static result back to the user. This means, whatever you see after the page is loaded within PHP is there to stay, unless you do one of two things:
1) Send a new request -- You provide different parameters, the page re-executes its logic and returns a new result to the user
2) Execute some form of clientside Javascript. Javascript is different from PHP in that it executes on the client (not the server) so you don't necessarily have to send responses back to the server unless you need more information. Javascript and PHP can be combined to create AJAX calls which allow the client to make asynchronous calls to the webserver for more data without reloading the entire page. The Javascript handles re-drawing the new information or updating the page which can appear seamless to the user.
What you therefore need is one of those two options. Either you provide 'next'/'previous' links to the user and the page is loaded differently each time or you create an AJAX call that fetches the url of the next image and then loads it.
Try assigning a variable to $gags[0][$index]. Something like
$imgsrc = $gags[0][$index];
and then
pic.src='<?php echo $imgsrc; ?>';

I seem to be unable to get AJAX/JS to reload a PHP script and update various page elements

So here is the situation. I'm building a page to host a radio stream hosted on an Icecast server. I got the player working great and cobbled together a PHP script to extract and parse out various data points from the server. Information such as current track, number of listeners, etc.
Here's the problem. It loads fine when the page is first opened, but I can't figure out a way to get these variables to be updated every 5-10 seconds or so and update the page with the new information WITHOUT reloading the page completely (it is a radio station after all, and having to re-buffer the station ever 10 seconds just isn't feasible.
Here's what I have so far, after various attempts have been removed from the code. Any ideas? I've seen it done for one or two variables, but I have almost a Dozen here...
<div id="current_song"></div>
<script language="javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script language="javascript">
{
$.ajax({
type: 'POST',
url: 'script.php',
data: 'getLatestInfo',
dataType: 'json',
cache: false,
success : function(dp){
$.getJSON('script.php', function(dp) {
//'data' will be the json that is returned from the php file
$.("#current_song").html("dp[9]");
});
getlatest();
};
});
}
</script>
and here is the PHP parser
<?php
Function getLatestInfo() {
$SERVER = 'http://chillstep.info:1984';
$STATS_FILE = '/status.xsl?mount=/test.mp3';
$LASTFM_API= '27c480add2ca34385099693a96586bd2';
//create a new curl resource
$ch = curl_init();
//set url
curl_setopt($ch,CURLOPT_URL,$SERVER.$STATS_FILE);
//return as a string
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
//$output = our stauts.xsl file
$output = curl_exec($ch);
//close curl resource to free up system resources
curl_close($ch);
//loop through $ouput and sort into our different arrays
$dp = array();
$search_for = "<td\s[^>]*class=\"streamdata\">(.*)<\/td>";
$search_td = array('<td class="streamdata">','</td>');
if(preg_match_all("/$search_for/siU",$output,$matches)) {
foreach($matches[0] as $match) {
$to_push = str_replace($search_td,'',$match);
$to_push = trim($to_push);
array_push($dp,$to_push);
}
}
$x = explode(" - ",$dp[9]);
echo json_encode($dp);
}
?>
I know it doesn't look pretty yet, but that's what CSS is for right?
Any ideas? Essentially I need the PHP script to rerun, update the variables, and rebuild the text output without touching the audio tag.
Javascript is code that executes client-side (on the website visitors machine) and PHP executes serverside. The way to insert content into a page without reloading the entire page is to use Javascript to inject code into the HTML. Now, for example, say that you have a PHP file on your server, called getLatest.php with a function called getLatestVariables() that finds out the latest values for all your variables and returns an array containing them. What you can do is use javascript to call getLatestVariables() from getLatest.php, and when the function returns the array, it will return it to the javascript. Once the array of variables has been returned to the javascript you can then insert the variabes into HTML divs without having to refresh the entire page.
to call the php function I suggest using jquery to perform an ajax call
also to insert the data returned from the php, jquery is your best bet too.
You need client side JavaScript for this. Get your hands on basic ajax books.
You can request the script for updated data every 5 seconds and update it on the page, this is complicated and needs some knowledge of JavaScript.
The script will have to be new too, or this one edited to trace type of request and return data accordingly.
var url="http://script-address"
var req = new XMLHttpRequest(); // Begin a new request
req.open("GET", url); // An HTTP GET request for the url
req.send(null);
This is how you can check the response
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
//we got a complete valid HTTP response
var response = req.responseText;
//code to handle response
}
php is a serverside language, so re-running the php inside your page will always result in the entire page refreshing, however if you use a javascript ajax call (I suggest using jquery) to a different php file, that php file can be executed serverside without affecting your page. you can then return the newly found variables from this php file to the javascript, and insert them in the callback of the ajax call.
see the answer to this question
If you need any more detail let me know...
$.getJSON('phpFileThatReturnsJSON.php', function(data) {
//'data' will be the json that is returned from the php file
$.("#idOfDivToInsertData").html("an item from the json array ie data['song']");
});
look at JQuery docs for ajax calls, if you've got this far you should be able to nail it out pretty quickly.
Also dont forget to include the jquery library in your html header...
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>

is progress bar possible with php and javascript using ajax

I was wondering how to make progress bar like gmail.
I tried
<script src="jquery.js"></script>
<script>
$(function (){
$.ajax({
url: 'index.php',
success: function(data) {
$('#bar').html(data);
}
});
})
</script>
<div id="bar"></div>
And on index.php
[EDIT]: by sleep() i just meant to simulate continuous stream of output like multithreaded programs which is not supported in php.
<?php
for($i=0; $i<=10; $i++)
{
sleep(1);
echo "$i";
}
it seems that output is echoed out at once so i get result 012345678910 at once.
also i tried
setInterval(function (){
$.ajax({
url: 'index.php',
success: function(data) {
$('#bar').html(data);
}
});
}, 1000);
Instead, i had trouble maintaining value of 'progress', so i did
<?php
session_start();
if(isset($_SESSION['value'])){
if($_SESSION['value'] >= 10)
{
unset($_SESSION['value']);
}
else
{
$_SESSION['value']++;
}
}
else
{
$_SESSION['value'] = 0;
}
echo $_SESSION['value'];
as part of my php. But it seems that, i am calling ajax function on continuous interval.
My Question is,
How does google use progress bar, while loginng in gmail. Do they get continuos 'stream' of data like i tried on my first example or send (regularly) request on some url (though not through ajax .. through JSONP or whatever) and upadate the page like second ?
Can I do same with php , even if not with php, can I do it using javascript and other server side scripting language where multithreading is supported?
I'm not sure what exactly Gmail does for the progressbar, but you can achieve something similar in PHP, although it may be a bit tricky.
First, to explain why your examples don't work:
If you echo and sleep, like your first example, it will never work. Ajax performs a full request - that is, if the response does not finish, it will wait. When you loop and sleep, the request is not "closed" until the PHP script has finished executing.
If you use session, like in the other example, the problem becomes the session store. The store is typically locked during script execution, and it will not update itself to allow for the type of progress check you want.
What you could do is write progress to a file (or to a database) manually. For example:
file_put_contents('progress.txt', 1);
Then, have another script read the file and output the contents.
This should work, because file_put_contents opens, writes and closes the file.
Using some other language than PHP would make it easier. Being multithreaded would possibly make it easier, but is not a requirement. However, having a continuously running process would make it simpler (PHP only runs a process for the duration of your request and then exits)
run your jquery code at an interval, and use PHP to print the progress percenage and draw the bar then.
so it will be something like
<script>
function bar()
{
var v=getProgress(...);
setTimeout("bar()",1000);
drawBar();
}
function drawBar(l)
{
//set div's length to l
}
</script>
EDIT 2
<?php
/* get the request and calculate the job completion percentage and echo it ! */
?>
I think Gmail shows progress when it loads all resources, like JS files. There are different ways to do this: you could dynamically include all resources with JS, or you could make all included JS files report that they've been loaded.
To make PHP output partial output, use this:
ob.php
<?php
ob_start();
for ($i = 0; $i < 100; $i++) {
echo "{$i}<br />";
ob_flush();
flush();
usleep(100000);
}
.htaccess
php_value output_buffering "0"
this thread and this link helped me to find out solution for the same problem, so i am providing it for the record:
test.php:
<?php
for($i=0; $i<100; $i++)
{ usleep(100000); //100ms
echo 'A'; ob_flush(); flush();
}
?>
test.html:
<body>
<button onclick='call()'>call</button>
<div id='progress'>...</div>
<script>
function fprogress(e)
{ document.getElementById('progress').innerHTML ='progress: '+e.loaded +'%'; }
function call()
{ var req = new XMLHttpRequest();
req.addEventListener("progress", fprogress, false);
req.open('GET', 'test.php', true); req.send(null);
}
</script>
</body>
... so test.php can be any JOB which doing some stuff... and while doing it ECHOes 100 characters (bytes) with flashing buffer.
As per my opinion, you can divide your login process in several parts and checks.
Every part check completed send response to your progress bar and progress bar width will increase such patterns. After that progress bar will send next request to your login process for step untill you will not get upto 100% login and redirect.

Categories