PHP + Mysql insert into + jQuery progress bar - php

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

Related

AJAX, how to return file name?

I Want to get a file name from recursive AJAX, but until now its doesnt work, in my code was like this
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>GET NAME</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="/assets/mediaelements/build/jquery.js"></script>
<script src="/assets/mediaelements/build/mediaelement-and-player.min.js"></script>
<link href="/assets/mediaelements/build/mediaelementplayer.min.css" rel="stylesheet" />
<script type="text/javascript" src="jquery.min.js"></script>
<script>
(function rekurse(){
setTimeout(function()
{
/* ---------------------------------- */
$.ajax({
type: "POST",
cache: false,
url: 'shift.php',
data: {offi: 'E:/DataText/OFFICE/BI/FAR1'},
success: function(data){
alert(data);
rekurse();
},
error: function(){
alert(data);
rekurse(); // recurse, if you'd like.
}
});
/* ---------------------------------- */
}, 1000);
})();
</script>
</head>
<body onload="rekurse();return false;">
</body>
<html><body
and on shift.php, its just like
<?PHP
//
CLEARSTATCACHE();
//
$grps = '_';
$offi = $_POST['offi'];
$temp = $offi.'/'.$grps.'*.*';
$arrs = GLOB( $temp );
$coun = COUNT( $arrs );
//
IF($coun<1):
ECHO json_encode("ok");
ENDIF;
//
$text = $offi."/call.htm";
$hand = FOPEN( $text, 'w' );
$text = FWRITE( $hand,"\r\n");
$hand = FCLOSE( $hand );
//
$file = $arrs[0];
$hand = FOPEN( $file, 'r' );
$temp = FREAD( $hand, FILESIZE( $file ) );
$hand = FCLOSE( $hand );
//
$arrs = EXPLODE(',',$temp);
IF( COUNT($arrs)>0 ):
ECHO json_encode($temp);
ELSE:
ECHO json_encode("ok");
ENDIF;
//
?>
What im missed this and sorry about my english
Thank You
Regard
Bambang
Recursive AJAX is a bed idea.
you just check code of your php file and make sure it work's properly then after you call ajax function to get a file name.
First call your php file manually and check the output.
just use code like below don't make it complex..
$.ajax({
type: "POST",
cache: false,
url: 'shift.php',
data: {offi: 'E:/DataText/OFFICE/BI/FAR1'},
success: function(data){
alert(data);
},
error: function(){
alert(data);
}
});

Jquery Update DIV with rsync progress

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>

Change PHP genereted image with jQuery

I have a following HTML and Javascript code:
<script type="text/javascript">
$(function() {
$('#form_1 input').on('change', function() {
val = $('input:radio[name=graf]:checked').val();
$.ajax({
type: 'POST',
data: ({graf_id: val}),
url: 'rrd_image.php',
success: function(data) {
$('#div_1 img').attr('src', data);
}
});
});
});
</script>
<div id="div_1">
<form id="form_1">
<input type="radio" name="graf" value="1">Daily
<input type="radio" name="graf" value="2">Weekly
<input type="radio" name="graf" value="3">Monthly
</form>
<img src="default.png">
</div>
And the rrd_image.php:
$graf_id = $_REQUEST['graf_id'];
$tmpfile = "/tmp/rrd.png";
// rrd_graph options...
rrd_graph($tmpfile, $options);
header( "Content-Type: image/png" );
header( "Content-Length: " . filesize( $tmpfile ) );
$fp = fopen( $tmpfile, 'rb' );
if( $fp ) { fpassthru( $fp ); }
fclose( $fp );
exit();
The rrd_graph.php itself is working, but when i click one radio-button, the HTML page
do not reload the right PHP generated rrd image.
The problem is your PHP file is returning an image, not a URL. What I would do is pass your graf value, along with a time string, in the query string and then tell JS to load that image instead
$(function() {
$('#form_1 input').on('change', function() {
var val = $('input:radio[name=graf]:checked').val();
var time = new Date().getTime();
$('#div_1 img').attr('src', 'rrd_image.php?graf_id=' + val + '&time=' + time);
});
});
You don't need AJAX anymore because the time parameter will always be different and thus your browser won't cache it.

Phonegap Android download data from remote server jsonp

Testing downloading data from remote Db using Phonegap Android and JSONP
Works perfectly in Browser (with php file on remote host and index both from localhost on my local machine and when on remote host) and in Ripple but zero data displaying when ported to Android via Phonegap..just the 'Details' text is displaying..no error..
My code :
**INDEX.html**
<!DOCTYPE html>
<html>
<head>
<title>json</title>
<script src="phonegap3.1.0.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/
1.6.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
var output = $('#output');
$.ajax({
url: 'http://mydomain.com.com/landmarks1.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var contact = '<p>'+item.name+'</p>'
+ '<p>'+item.address+'</p><hr>';
$("#mylbl").append(contact);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
});
</script>
</head>
<body>
<div>
Details
<span id="mylbl"></span>
</div>
</body>
</html>
**landmarks1.php**
<?php
header('Content-type: application/json');
mysql_connect("localhost","m560847_sean","1994martha");
mysql_select_db("m560847_contacts");
$result = mysql_query("SELECT * FROM contact");
$records = array();
echo mysql_error();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
I've given access to remote domain in my xml file
<access origin="http://127.0.0.1*" />
<access origin="http://mydomain.com.com*" />
<access origin=".*"/>
I've looked at many many similar issues on here and in general on web and am stumped..

jQuery Ajax - Alternate XML sources for each request

I have two XML sources to retrieve data from. I want to use them alternately per page load. So when someone visits the page the first source will be used, next time the visit the page the other source will be used. Here is the ajax request I am using to get one data source:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "source1.xml", //how do I alternately load two different xml data sources?
dataType: "xml",
success: function(xml) {
var counter = 0
var output = '<li>';
$(xml).find('person').each(function(){
counter++;
var image = $(this).find('image').text();
var name = $(this).find('name').text();
var title = $(this).find('title').text();
var company = $(this).find('company').text();
output = output + '<div><img src=img/' + image + '.jpg />' + '<br /><label><span>' + name + '</span><br />' + title + '<br />' + company + '</label><br /></div>';
if(counter % 3 === 0){
output = output + '</li><li>';
}
});
output = output + '</li>';
$('#update-target ul').html(output);
}
});
});
For extra info, here is how I am alternately loading 2 flash files using PHP:
if(isset($_SESSION['rotation'])){
$picker = $_SESSION['rotation'];
}else{
$picker = rand(0,1);
}
if($picker == 0){
echo '<script type="text/javascript">
var video1 = new SWFObject("somefile1.swf", "p1", "151", "590", "9", "#ffffff");
video1.addParam("wmode","transparent");
video1.write("meh");
</script>';
$_SESSION['rotation'] = ++$picker;
} else {
echo '<script type="text/javascript">
var video1 = new SWFObject("somefile2.swf", "p1", "151", "590", "9", "#ffffff");
video1.addParam("wmode","transparent");
video1.write("meh");
</script>';
$_SESSION['rotation'] = --$picker;
}
I realize I could just stick the jquery document ready code right in there where I have the js calling the flash but it does not seem like a very efficient way of handling this. What is a "best case" way to do this?
You can just use a variable to keep it short, like this:
echo '<script type="text/javascript">var xmlSource = "source1.xml";</script>';
Use that in an if caluse as well, then just reference that in your code:
url: xmlSource,
There are other ways of course, using a cookie (the cookie plugin), putting the text right in the document.ready handler, etc...whichever seems most elegant to you I suppose.
I recommend the variable from the PHP side or a cookie...both of these options allow the document.ready code to stay outside the page in an external script, and not downloaded by the user each time.

Categories