I'm working on a file that already has some code, and it uses php's ob_start() and ob_get_clean() functions around the jQuery being used. Is there a clear reason for why someone would do this?
ob_start();
?>
<script>
$(document).ready(function() {
$('div.scripture').on('click', function() {
$('div#schedule div.text').slideUp();
text = $(this).next('div.text');
if (text.is(":visible") == true) {
text.slideUp();
} else {
text.slideDown();
}
});
});
</script>
<?php
$additionalJS = (!empty($additionalJS)) ? $additionalJS : NULL;
$additionalJS .= ob_get_clean();
Related
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'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>
My PHP code is:
<?php
class Sample{
public $name = "N3mo";
public $answer = "";
}
if( isset( $_GET['request'] ) ){
echo "Starting to read ";
$req = $_GET[ 'request' ];
$result = json_decode($req);
if( $result->request == "Sample" ){
$ans = new Sample();
$ans->answer = " It Is Working !!! ";
echo json_encode($ans);
}else{
echo "Not Supported";
}
}
?>
Is there anything wrong
I want to send a JSON to this php and read the JSON that it returns using java script , I can't figure out how to use JavaScript in this , because php creates an html file how Can I use $_getJson and functions like that to make this happen ?!
I tried using
$.getJSON('server.php',request={'request': 'Sample'}) )
but php can't read this input or it's wrong somehow
thank you
try this out. It uses jQuery to load contents output from a server URL
<!DOCTYPE html>
<html>
<head>
<title>AJAX Load Test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function(event) {
$('#responce').load('php_code.php?request={"request":"Sample"}');
});
});
</script>
</head>
<body>
<p>Click on the button to load results from php_code.php:</p>
<div id="responce" style="background-color:yellow;padding:5px 15px">
Waiting...
</div>
<input type="button" id="button" value="Load Data" />
</body>
</html>
Code below is an amended version of your code. Store in a file called php_code.php, store in the same directory as the above and test away.
<?php
class Sample
{
public $name = "N3mo";
public $answer = "";
}
if( isset( $_GET['request'] ) )
{
echo "Starting to read ";
$req = $_GET['request'];
$result = json_decode($req);
if( isset($result->request) && $result->request == "Sample" )
{
$ans = new Sample();
$ans->answer = " It Is Working !!! ";
echo json_encode($ans);
}
else
{
echo "Not Supported";
}
}
Let me know how you get on
It would be as simple as:
$.getJSON('/path/to/php/server.php',
{request: JSON.stringify({request: 'Sample'})}).done(function (data) {
console.log(data);
});
You can either include this in <script> tags or in an included JavaScript file to use whenever you need it.
You're on the right path; PHP outputs a result and you use AJAX to get that result. When you view it in a browser, it'll naturally show you an HTML result due to your browser's interpretation of the JSON data.
To get that data into JavaScript, use jQuery.get():
$.get('output.html', function(data) {
var importedData = data;
console.log('Shiny daya: ' + importedData);
});
I'm new to php and trying to create a simple script.. but I don't know if what i'm trying to do is possible with ob_start() please let me know, thanks.
here is my code:
<?php
ob_start();
if($mystuff !== 0) { foreach($mystuff['sirf7alk'] as $mystuff) {
?>
<?php include('header.php'); ?>
App name: <?php echo $mystuff->app; ?>
<?php include('footer.php');?>
<?php
} }
file_put_contents('page.php', ob_get_contents());
?>
that's what my code outputs:
my header content
App name: My app name
my footer content
here is what i want to achieve:
<?php include('header.php'); ?>
App name: My app name
<?php include('footer.php');?>
You need to output the PHP code, as opposed to running it. Treating it as a string will do that:
ob_start();
if ($mystuff !== 0) {
foreach($mystuff['sirf7alk'] as $mystuff) {
echo "<?php include 'header.php' ?>".PHP_EOL;
echo "App name: {$mystuff->app}".PHP_EOL;
echo "<?php include 'footer.php' ?>".PHP_EOL;
}
}
$output = ob_get_contents();
file_put_contents('page.php', $output);
Now that the actual question is answered... It may be fun to control output buffering in this way, but it is probably not the best idea in the world, which is to say that there are better ways of achieving the same result. E.g. simply using an auxiliary variable, which holds the otherwise output buffered content, is a much saner approach:
$output = '';
if ($mystuff !== 0) {
foreach($mystuff['sirf7alk'] as $mystuff) {
$output .= "<?php include 'header.php' ?>".PHP_EOL;
$output .= "App name: {$mystuff->app}".PHP_EOL;
$output .= "<?php include 'footer.php' ?>".PHP_EOL;
}
}
file_put_contents('page.php', $output);
<?php
ob_start();
if($mystuff !== 0) { foreach($mystuff['sirf7alk'] as $mystuff) {
echo "<?php include('header.php'); ?>\n";
?>
App name: <?php echo $mystuff->app; ?>
<?php
echo "<?php include('footer.php');?>\n";
} }
file_put_contents('page.php', ob_get_contents());
?>
Should do it. You must echo the whole include lines as strings to avoid php from parsing it
I like to get a dir listing in php
glob("*.jpg");
or
$dir = '.'; //requested directory to read
$notthat = array('.', '..'); //what not to include
$listedfiles = array_diff(scandir($dir), $notthat); // removed what not to include
so i like to send that array to a javascript like that (slides = $listedfiles)
function startSlideshow(slides) { .. do something..}
What is the best way to do that ?
json_encode is your friend for this. No looping is necessary. It will return a pure json object string that you can then just echo into your js file using PHP. Example:
var slides = <?php echo json_encode( $filelistarray );?>
function startSlideshow(slides) { .. do something..}
you can always just do an echo of it to a javascript :
echo ' <script type="text/javascript">
var filelist = [];
';
foreach($listedfiles as $file)
{
echo " filelist[] = $file; ";
}
echo "</script>";
PHP and Javascript cannot directly interact, however, you can output Javascript from PHP the same way you can output plain text or HTML:
<script type="text/javascript">
var slides = [];
<?php
foreach ($listedfiles as $file)
{
echo "slides[] = '" . addslashes($file) . "';\n";
}
?>
// ... do js stuff
</script>
Basically, after creating your array in PHP, you output the JS code to create the same array in javascript.