I'm trying to update a DIV with the ongoing output from an rsync command. The idea being I can see how the download is progressing.
This is the code I've got, but I'm getting errors relating 'Uncaught SyntaxError: Unexpected token ILLEGAL'
<?php
$down = popen('rsyncd -Pav http://ipv4.download.thinkbroadband.com/1GB.zip 1GB.zip', 'r');
while($progress = fgets($down, 124)) {
ob_flush();flush();
?>
<script type="text/javascript">
$(document).ready(function() {
var update = "<?php echo $progress; ?>";
$("#status").html(update);
});
</script>
<?php
ob_flush();
ob_flush();flush();
}
pclose($down);
}
?>
<div id="status"></div>
In the console I can see that it relates to :
var update = " 33390592 46% 4.62MB/s 0:00:08
34701312 48% 4.63MB/s 0:00:07
35979264 50% 4.63MB/s 0:00:07
";
How can I get each line of update and show it in a DIV without getting errors ?
Thanks
UPDATE
I'm now using this. The php echo for $update shows the output live in the web page, but the DIV is not updated until the page completes and then I only get the last line of output.
Why does the php echo work, but the jquery update to the div now work as expected ?
<?php
$down = popen('rsyncd -Pav http://ipv4.download.thinkbroadband.com/1GB.zip 1GB.zip', 'r');
$order = array("\r\n", "\n", "\r");
while($progress = fgets($down, 32)) {
ob_flush();flush();
$update = str_replace($order,'<br />', $progress);
echo $update; // <-- this outputs fine.
?>
<script type="text/javascript">
$(document).ready(function() {
var update = "<?php echo $update; ?>";
$("#status").html(update);
});
</script>
<?php
ob_flush();flush();
}
pclose($down);
}
?>
Is this due to the jquery not running until the page is fully loaded, so the div is only updated with the last entry of $update ?
If so is there any way to have the jquery run as the page is loading so the DIV is updated ?
Thanks :)
Thanks
UPDATE
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({ cache: false });
$("#test").click(function () { $("#log").load("go.php"); });
});
</script>
Just tried the above, it works and calls go.php and I get the output but only when go.php has finished the rsync download. any way to show the ongoing output whilst the download happens ?
use str_replace() php function
<?php
$order = array("\r\n", "\n", "\r");
$replace = '<br />';
?>
<script type="text/javascript">
$(document).ready(function() {
var update = "<?php echo str_replace($order, $replace, $progress); ?>";
$("#status").html(update);
});
</script>
Related
I have problem with showing current inserted rows into mysql with query.
Now I have this code in index.php:
$('#nacitatATC').click(function() {
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.addEventListener("progress", function(e){
var p = (e.loaded / e.total)*100;
var prave = $("#progress").html();
$("#progress").html(prave+"<br>"+p);
});
return xhr;
}
, type: 'post'
, cache: false
, url: "/sql.php"});
});
});
and in sql.php I have the php code with inserting data into mysql with for().
$i is the current inserting line and $pocet is total lines.
The problem is with show current inserting line with ajax.
The code above shows in div #progress "100" when ajax finish loading.
I need show 1% 2% 3% 4%... 99% 100% Completed.
Thanks for help!
I think php -> flush() is what you are looking for.
This Example works perfect on my php-apache on debian
see ajax-request-progress-percentage-log
PHP side:
header( 'Content-type: text/html; charset=utf-8' );
echo 'Begin ...<br />';
for( $i = 0 ; $i < 10 ; $i++ )
{
echo $i . '<br />';
flush();
ob_flush();
sleep(1);
}
echo 'End ...<br />';
site:& javascript:
<!doctype html>
<html>
<head>
<title>Test Flush</title>
<meta charset="utf-8">
<script src="./js/jquery-2.0.3.min.js" type="text/javascript"></script>
<body>
<h1>Hello</h1>
<div id="progress">0%</div>
<p>
</p>
<script type="text/javascript">
$('h1').click(function() {
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.addEventListener("progress", function(e){
console.log(e.currentTarget.response);
$("#progress").html(e.currentTarget.response);
});
return xhr;
}
, type: 'post'
, cache: false
, url: "testFlush.php"
});
});
</script>
</body>
Also have a look at Rogers Answer in
how-to-flush-output-after-each-echo-call
He found issues in the apache setup
I am writing an application in JQTouch, and am using a big red button
Red
I am using PHP to dynamically build the JQT page with multiple divs. The app is a server management console that gets data from MySQL. My idea is that I use a While loop to make a div for each server returned in the MySQL query, and each div will have a delete server button(the big red button). I have to call the dame bit of code because of the whole dynamic page generating thing. So I was wondering if there was a way I could have the onClick function that I call with the button
Red
know what div the button is in that is calling the function. There will be a button in multiple divs that call the same code, but i have to know WHAT server to delete. Any suggestions?
Here is the full source code.
<html>
<link rel="stylesheet" href="jq_touch/themes/css/jqtouch.css" title="jQTouch">
<script src="jq_touch/src/lib/zepto.min.js" type="text/javascript" charset="utf-8"></script>
<script src="jq_touch/src/jqtouch.min.js" type="text/javascript" charset="utf-8"></script>
<!-- Uncomment the following two lines (and comment out the previous two) to use jQuery instead of Zepto. -->
<!-- <script src="../../src/lib/jquery-1.7.min.js" type="application/x-javascript" charset="utf-8"></script> -->
<!-- <script src="../../src/jqtouch-jquery.min.js" type="application/x-javascript" charset="utf-8"></script> -->
<script src="../../extensions/jqt.themeswitcher.min.js" type="application/x-javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
var jQT = new $.jQTouch({
icon: 'jqtouch.png',
icon4: 'jqtouch4.png',
addGlossToIcon: false,
startupScreen: 'jqt_startup.png',
statusBar: 'black-translucent',
themeSelectionSelector: '#jqt #themes ul',
preloadImages: []
});
// Some sample Javascript functions:
$(function(){
// Show a swipe event on swipe test
$('#swipeme').swipe(function(evt, data) {
var details = !data ? '': '<strong>' + data.direction + '/' + data.deltaX +':' + data.deltaY + '</strong>!';
$(this).html('You swiped ' + details );
$(this).parent().after('<li>swiped!</li>')
});
$('#tapme').tap(function(){
$(this).parent().after('<li>tapped!</li>')
});
$('a[target="_blank"]').bind('click', function() {
if (confirm('This link opens in a new window.')) {
return true;
} else {
return false;
}
});
// Page animation callback events
$('#pageevents').
bind('pageAnimationStart', function(e, info){
$(this).find('.info').append('Started animating ' + info.direction + '… And the link ' +
'had this custom data: ' + $(this).data('referrer').data('custom') + '<br>');
}).
bind('pageAnimationEnd', function(e, info){
$(this).find('.info').append('Finished animating ' + info.direction + '.<br><br>');
});
// Page animations end with AJAX callback event, example 1 (load remote HTML only first time)
$('#callback').bind('pageAnimationEnd', function(e, info){
// Make sure the data hasn't already been loaded (we'll set 'loaded' to true a couple lines further down)
if (!$(this).data('loaded')) {
// Append a placeholder in case the remote HTML takes its sweet time making it back
// Then, overwrite the "Loading" placeholder text with the remote HTML
$(this).append($('<div>Loading</div>').load('ajax.html .info', function() {
// Set the 'loaded' var to true so we know not to reload
// the HTML next time the #callback div animation ends
$(this).parent().data('loaded', true);
}));
}
});
// Orientation callback event
$('#jqt').bind('turn', function(e, data){
$('#orient').html('Orientation: ' + data.orientation);
});
});
</script><?php
//Connect
mysql_connect("localhost", "root", "root") or die(mysql_error());
//Make and store queries
mysql_select_db("servermgr") or die(mysql_error());
$result = mysql_query("SELECT * FROM servers")
or die(mysql_error());
//Echo some constant HTML
echo'<div id="serverset">';
echo'<div class="toolbar">';
echo'<h1>Servers Home</h1> ';
echo'</div>';
echo'<ul class="rounded">';
//Begin printing out MYSQL rows (List Items)
while($row = mysql_fetch_array( $result )) {
//$row_friendlyName = $_row['friendly_name']
$friendlyName_noSpaces = str_replace(' ', '_', $row[friendly_name]);
echo'<li class="">'.$row["friendly_name"].'</li>';
}
//Close list
echo'</ul>';
echo '</div>';
//Redo all previous queries to print out the divs
mysql_select_db("servermgr") or die(mysql_error());
$result2 = mysql_query("SELECT * FROM servers")
or die(mysql_error());
while($row2 = mysql_fetch_array( $result2 )) {
$friendlyName_noSpaces2 = str_replace(' ', '_', $row2[friendly_name]);
echo '<div id="'.$friendlyName_noSpaces2.'">';
echo'<div class="toolbar">';
echo'<h1>'.$row2[friendly_name].'</h1> ';
echo 'Back';
echo'</div>';
echo'<ul class="rounded">';
echo '<li>Friendly Name: '.$row2[friendly_name].'</li>';
echo '<li>IP Address: '.$row2[ip].'</li>';
echo '<li>Server Hostname: '.$row2[hostname].'</li>';
echo '<li>MAC Address: '.$row2[MAC].'</li>';
echo'</ul>';
echo'<button href="#" class="redButton">Red</button>';
echo'</div>';
}
//END OF PHP
?>
</body>
</html>
add a data attribute to your "Big Red Button" as follows
Red
and from your handling code retrieve the data value as follows
var server = $(this).attr('data-server');
Then you can do your condition logic.
DevZer0's answer is probably what you want to go with but an alternative approach is to add a class to the containing div like
echo '<div id="'.$friendlyName_noSpaces2.'" class="server">';
Then you can do this in your callback
var server = $(this).closest(".server").attr("id");
to get the id of the containing div.
I have a download page. Members are free to click on their bought songs and the download starts. I wish now that in the same time an Ajax request takes place, which adjusts the count of downloads in the database. The page should then be reloaded to the counter from the database is updated again. If the counter is zero, there is no longer downloading.
Obviously my script does not work. The download happens, but the JQuery-Script will not work. Does someone have a solution?
This is the link to the download-page:
<a href="get-download-files.php?file=xyz.zip"><img class="a_0" src="images/download.png" width="30" height="30" />XYZ-Song/a>
And this is the Java-Script on the same page:
<script>
$(document).ready(function(){
$(".a_0").click(function(){
$.get("zaehler.php?dl_id=1", function(data){
$("#ausgabe").html(data);
});
});
});
</script>
And this is the request-file:
<?php
require_once 'includes/db_login.php';
$dl_id = $_REQUEST['dl_id'];
// counter updaten
$sql = 'UPDATE ' . $tbl_prefix . 'downloads
SET zaehler = zaehler - 1
WHERE dl_id = ' .$dl_id;
mysql_query($sql);
$abfrage = 'SELECT zaehler FROM ' . $tbl_prefix . 'downloads WHERE dl_id=' . $dl_id;
$ergebnis = mysql_query($abfrage);
while ($datensatz = mysql_fetch_array($ergebnis, MYSQL_ASSOC))
{
echo '<h3 style="color:#333;">Dein Download-Stand</h2>';
echo '<br /><br />Du hast noch ' . $datensatz['zaehler'] . ' Downloads zugut.';
}
?>
Im thanking you. Best regards,
Heinz
You don't need Ajax for this. In the script get-download-files.php, update the database before delivering the file to the browser.
Have you tried this?
<script>
$(document).ready(function(){
$(".a_0").click(function(){
$("#ausgabe").load("zaehler.php?dl_id=1");
});
});
</script>
You can check if your code is executed by adding a alert() inside your function. If the alert fires, the function is executed.
<script>
$(document).ready(function(){
$(".a_0").click(function(){
alert('Function is fired!'); // Debug
$("#ausgabe").load("zaehler.php?dl_id=1");
});
});
</script>
so I have a Ajax-Scripts thats permanently reloads a PHP-Page:
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
loadstatus();
});
function loadstatus(){
$.ajax("innopbx.monitor.php").done(function(data){
document.getElementById("status").innerHTML = data;
setTimeout('loadstatus()', 1000);
});
}
</script>
And the PHP-Page being reloaded shows HTML-Canvas like this:
echo '<canvas id="' . $ui->guid . '" width="100" height="100" class="clear" style="border:1px dotted"></canvas> ';
echo '<script type="text/javascript">
var a_canvas = document.getElementById("' . $ui->guid . '");
var a_context = a_canvas.getContext("2d");
var gradient = a_context.createLinearGradient(0, 0, 0, 100);
gradient.addColorStop(0, "#bbffbb");
gradient.addColorStop(1, "#55ff55");
a_context.fillStyle = gradient;
a_context.fillRect(2, 2, 96, 96);
a_context.font = "10px sans-serif";
a_context.fillStyle = "black";
a_context.fillText("' . $ui->cn . '", 5, 20);
</script>';
When I navigate to the PHP-Page directly the Canvas is drawn exactly as expected. But when I navigate to the Page with the AJAX-Function that reloads the PHP-Page permanently I only see the dotted border. Its not filled and no Text is there.
Do you have any idea? Thanks in advance!
You can try to add document.getElementById("status") as target parameter of $.ajax.
var t = document.getElementById("status");
function loadStatus(){
$.ajax({url: "innopbx.monitor.php", target: t, success: function(){
setTimeout(loadstatus, 1000);
});
}
It should deal with the js execution, rather than innerHTML = ....
How do I pass a variable in a php file that is loaded into a page (DOM) to a jQuery function??
Iv'e tried various method's while searching online but I haven't figured out how to use them correctly.
I need the var navHeaderTitle to be passes to the jQuery load() callback function so it sets the HTML tag, #navHeaderTitle, to the variable called in the php file.
Thnx for you help.
php:
<?php
$con = mysql_connect("localhost","user","pw");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("SELECT * FROM some_list");
$navHeaderTitle = "MY NEW TITLE";//<--I NEED 2 INJECT THIS!!
while($row = mysql_fetch_array($result))
{
echo "<div id='navItem' title='$navHeaderTitle'>";
echo "<h1>" . $row['label'] . "</h1>";
echo "<h2>" . $row['title'] . "</h2>";
echo "<p>" . $row['description'] . "</p>";
echo "</div>";
}
mysql_close($con);
?>
JavaScript in the HTML Head:
<script type="text/javascript">
var navHeaderTitle = '';
$(document).ready(
function() {
$("#navContent").load('http://url/my_list.php', function() {
$('#navHeaderTitle').text($(html).find('div#navItem').attr('title'));//<--GET THE VAR FROM LOADED PHP FILE!!
});
});
</script>
<body>
<div id="navPanel">
<div id="navHeader">
<img src="images/ic_return.png" style="float: left;"/>
<img id="listSortBtn" src="images/ic_list_sort.png" style="float: right;"/>
<h4 id="navHeaderTitle"></h4>//THIS IS WHAT NEEDS THE VAR DATA!!
</div>
<div id="navScrollContainer" class="navContentPosition">
<div id="navContent">HTML CONTENT from PHP GETS DUMPED IN HERE</div>
</div>
</div>
</body>
Ive tried using this but not sure how to:
$.get('scripts/my_list.php', {}, function(data){
data = split(':');
})
I would have the php file return a json object that contains two parts, the html you want to echo and the title you want to use.
Then I would use jQuery's .ajax() function instead of .load() to get the return value from your php script in a javascript variable instead of dumping it directly as .load() does.
replace echo("$navHeaderTitle"); with
echo("<script> var navHeaderTitle = $navHeaderTitle </script>");
and remove var navHeaderTitle = ''; from the <head> script..
that will setup a JS variable like you're using, but you have to do that before the code in the <head> loads...
EDIT
ok don't echo("$navHeaderTitle"); you can put it into the HTML like:
echo "<div id='navItem' title='$navHeaderTitle'>";
then in the JS you can do:
<script type="text/javascript">
var navHeaderTitle = '';
$(document).ready(
function() {
$("#navContent").load('http://url/my_list.php', function(response) {
$('#navHeaderTitle').text($(response).attr('title'));
});
});
</script>
here's a jsfiddle demo: http://jsfiddle.net/JKirchartz/hdBzF/ (it's using fiddle's /echo/html/ so the load has some extra stuff to emulate the ajax)
It would be cleaner to pass the var in a custom attribute (data-var), then fetch it width JQuery
$(some_element).attr("data-var");
I hate to mess my JS code with php.