Load page while PHP is executing - php

What Im trying to do: Display a loading gif or text... at the very least show a black screen before and during the time the php is being executed.
What I have tried.
I have tested using flush () and I get nothing until the entire php process is finished. I dont particularly like this concept either but I'll take anything.
I am considering using two pages to accomplish this though the current project is nearly complete and would take some time to consolidate the scattered html/php code.
Currently I'm doing 3-simpleXML_load_file(), 1-include(), 1-file_get_contents()
I have javascript function plotting data from one of the simpleXML_Load_file()...
Im up for moving parts of the code to a different file but it's a big task. So id like some advise or suggestions on how to proceed.
If I need to elaborate more just ask!
Thanks,
JT
<html>
<head>
<?php
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
$weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');
?>
<script type="text/javascript">
<!--Plot function-->
$(function()
{
var d =
[
<?php
//Pulling in hourly data to plot temp vs time
$i=0;
$array=array();
while ($i<=100)
{
echo '['. (strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000) .','.$weather_hourly->data->parameters->temperature->value[$i] .'],';
$value = $weather_hourly->data->parameters->temperature->value[$i];
array_push($array,$value);
$i++;
}
foreach ($array as $key => $value)
{
$value = (string) $value;
$min_sec_array[] = $value;
}
?>
</script>
</head>
<body>
<div id=graph>
</div>
</body

The main way you can accomplish this is by using AJAX and multiple pages. To accomplish this, the first page should not do any of the processing, just put the loading image here. Next, make an AJAX request, and once the request is finished, you can show the results on the page or redirect to a different page.
Example:
File 1 (jQuery must be included also), put this in the body along with the loader animation:
<script language="javascript" type="text/javascript">
$(function(){
var mydata = {};
$.post('/myajaxfile.php', mydata, function(resp){
// process response here or redirect page
}, 'json');
});
</script>
Update: Here is a more complete example based on your code. This has not been tested and needs to have the jQuery library included, but this should give you a good idea:
File 1: file1.html
</head>
<body>
<?php
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
?>
<!-- Include jQuery here! Also have the loading animation here. -->
<script type="text/javascript">
$(function(){
$.get('/file2.php?Lat=<?php echo $lat; ?>&Lon=<?php echo $long; ?>', null, function(resp){
// resp will have the data from file2.php
console.log(resp);
console.log(resp['min_sec_array']);
console.log(resp['main']);
// here is where you will setup the graph
// with the data loaded
<!--Plot function-->
}, 'json');
});
</script>
<div id=graph>
</div>
</body
</html>
File 2: file2.php
I'm not sure if you needed the $min_sec_array, but I had this example return that as well as the main data you were using before.
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
$weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');
//Pulling in hourly data to plot temp vs time
$i=0;
$main = array();
$array=array();
while ($i<=100)
{
$main[] = array((strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000), $weather_hourly->data->parameters->temperature->value[$i]);
$value = $weather_hourly->data->parameters->temperature->value[$i];
array_push($array,$value);
$i++;
}
foreach ($array as $key => $value)
{
$min_sec_array[] = (string) $value;
}
echo json_encode(array(
'min_sec_array' =>$min_sec_array,
'main' => $main
));
exit();
?>

I would recommend not to do this with plain html and php if u expect it modify the page after it is loaded. Because php is server side processing, so it is executed before the page is send to the user. U need Javascript. Using Javascript will enable u to dynamically add or remove html elements to or from the DOM tree after the page was send to the user. It is executed by the users browser.
For easier start I would recommend jQuery, because there are lots of tutorials on such topics.
JQuery
JQuery learning center
A small example:
HTML
<head>
<meta charset="utf-8" />
<title> </title>
<script type="text/javascript" src="js/lib/jquery-1.9.1.js"></script>
</head>
<body>
<h1>Addition</h1>
<div id="error_msg"> </div>
<div id="content">
<!-- show loading image when opening the page -->
<img src="images/loading.gif"/>
</div>
<script type="text/javascript">
// your script to load content from php goes here
</script>
</body>
this will be nothing more then the following until now:
adding the following php file
<?php
$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
$result = $num1 + $num2;
echo '<p>Calculating '.$num1.' + '.$num2.' took a lot of time, but finally we were able to evaluate it to '.$result.'.</p>'
.'<p> '.$num1.' + '.$num2.' = '.$result.'</p>';
?>
wont change anything of the html, but adding javascript/ Jquery inside the HTML will be kind of connection between static html and server side php.
$(document).ready(function(){
$.ajax({ // call php script
url: 'php/script.php?num1=258&num2=121',
type:'GET',
timeout: 500,
contentType: 'html'
}).success(function(data){
// remove loading image and add content received from php
$('div#content').html(data);
}).error(function(jqXHR, textStatus, errorThrown){
// in case something went wrong, show error
$('div#error_msg').append('Sorry, something went wrong: ' + textStatus + ' (' + errorThrown + ')');
});
});
This will change your page to show the loading animation until the php script returns its data, like:
So you can setup the whole page in plain html, add some loading gifs, call several php scripts and change the content without reloading the page itself.

It is kind of nasty solution to your problem...
But this can work:
You work with those -
ob_start();
//printing done here...
ob_end_flush();
at the beginning you will create your rotating ajax gif...
Then you do all the processing and calculating you want...
At the end of the processing, just echo a small script that does a hide to your gif...
Depends on the exact need, maybe ajax can be more elegant solution.

In response to your conversation with David Constantine below, did you try using ob_flush()?
ob_start();
echo '<img src="pics/loading.gif">';
ob_flush();
// Do your processing here
ob_end_flush();

I think you don't have a problem with flushing your PHP output to the browser, but more likely with getting the browser to start rendering the partial html output. Unfortunately, browser behavior on partial html is browser-specific, so if you want something to work the same in any browser, the AJAX solution suggested in other answers is the better way to go.
But if you don't like that added complexity of a full AJAX solution, you can try to make your html output "nice" in the sense of providing some body output that can be formatted without needing the rest of the html output. This is were your sample code fails: It spends most of its time outputting data into a script tag inside the html header. The browser never even sees the start of the body until your PHP code has practically finished executing. If you first write your complete body, then add the script tag for the data there, you give the browser something to at least try to render whilst waiting for the final script to be completed.
I've found the same issue (albeit not in PHP) discussed here: Stack Overflow question "When do browsers start to render partially transmitted HTML?" In particular, the accepted answer there provides a fairly minimal non-AJAX example to display and hide a placeholder whilst the html file hasn't completely loaded yet.

I know this is an old question, but the answer provided in this page by rpnew is extremely clear and easy to adjust to your project's requirements.
It is a combination of AJAX and PHP.
The HTML page PHPAjax.html which calls the PHP script:
<html>
<head>
<script type="text/javascript">
document.write('<div id="loading">Loading...</div>');
//Ajax Function
function getHTTPObject()
{
var xmlhttp;
if (window.ActiveXObject)
{
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E)
{
xmlhttp = false;
}
}
}
else
{
xmlhttp = false;
}
if (window.XMLHttpRequest)
{
try
{
xmlhttp = new XMLHttpRequest();
}
catch (e)
{
xmlhttp = false;
}
}
return xmlhttp;
}
//HTTP Objects..
var http = getHTTPObject();
//Function which we are calling...
function AjaxFunction()
{
url='PHPScript.php';
http.open("GET",url, true);
http.onreadystatechange = function()
{
if (http.readyState == 4)
{
//Change the text when result comes.....
document.getElementById("content").innerHTML="http. responseText";
}
}
http.send(null);
}
</script>
</head>
<body onload="AjaxFunction()">
</body>
</html>
The Background PHP Script PHPScript.php:
<?php
sleep(10);
echo "I'm from PHP Script";
?>
Save both files in the same directory. From your browser open the HTML file. It will show 'Loading...' for 10 seconds and then you will see the message changing to "I'm from PHP Script".

Related

How to embed or include php file in the innerHTML in ajax?

I want to display the contents of the php file and I tried to include the php file in ajax but it doesn't work.
solution 1 doesn't work
document.getElementById("txtMeaning").innerHTML = "<center><img src='images/img_layout/exploro_logo.png'><?php include 'word.php' ?></center>";
solution 2 still doesn't work
document.getElementById("txtMeaning").innerHTML = "<center><img src='images/img_layout/exploro_logo.png'<script type='text/javascript' src='wotd.php'></script>";
Here's the code for ajax if there's no input it will display the word of the day
function showMeaning(word)
{
if(word.length == 0)
{
document.getElementById("txtMeaning").innerHTML = "<center><img src='images/img_layout/exploro_logo.png'><?php include 'word.php' ?></center>";
//the word of the day must be displayed here but it doesn't work
return false;
}
else{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url = "get_word.php"
url = url + "?word=" + word
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
}
here's my php code for generating the word of the day
<?php
$con=mysql_connect("localhost","root","");
mysql_set_charset("UTF8", $con);
if(!$con)
{
die("Could not connect." .mysql_error());
}
mysql_select_db("dictionary_ajax", $con);
$query = "SELECT eng_word" .
" FROM english".
" ORDER BY RAND(DAY(NOW())) LIMIT 1";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);
if($num_rows==0)
{
echo "No Results Found. Please try again";
}
while($row=mysql_fetch_array($result))
{
echo "<center><div class='wotd'>Word of the day:</div><div class='word'>".$row['eng_word']."</div></center>";
}
mysql_close($con);
?>
A better approach would be to call the php file via an AJAX request and then append the response to the relevant DOM element.
Overview of AJAX using vanilla Javascript:
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
Docs on JQuery Post and Get short cuts.
https://api.jquery.com/jquery.get/
http://api.jquery.com/jquery.post/
There are examples of what you are trying to do in the JQuery .get docs
Using jQuery, you could you use one of their ajax calls to load your html from include.php.
<div id="content"></div>
<script>
$(document).ready(function() {
$("#content").load("/yourpath/include.php");
});
</script>
or, without using jQuery, you may try this,
<div id ="content"></div>
<script>
function loadphpfile() {
var x = document.getElementById("content");
x.innerHTML = '<?php include_once "include.php";?>';
}
loadphpfile();
</script>
Try isolating the html+js files and API call yout .php file
app |-- www/index.html
|-- www/js/main.js
|-- www/api/word.php
Create html for view and include your javascript file and the jQuery library.
Get your data from the php file and return a json file
Call the *.php api file url using $.ajax Read more
Update DOM from the ajax data object
Hope that helps
You should make an AJAX call to get HTML from your server, then put the response to a DOM element with JavaScript.
So, in your case this may look like:
<center>
<img src="images/img_layout/exploro_logo.png">
<div id="wordOfTheDay"></div>
</center>
<script type="text/javascript">
/**
* Gets a word of the day
*/
function getWordOfTheDay() {
//Makes AJAX call
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
//Adds the response to the DOM element with ID wordOfTheDay
document.getElementById("wordOfTheDay").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "word.php", true);
xhttp.send();
}
//Invoke the function to get the word of the day
getWordOfTheDay();
</script>
With a popular framework like jQuery, this may look like this:
<center>
<img src="images/img_layout/exploro_logo.png">
<div id="wordOfTheDay"></div>
</center>
<script type="text/javascript">
/**
* Gets a word of the day
*/
function getWordOfTheDay() {
//Makes AJAX call
$.get("word.php", function (response) {
$('#wordOfTheDay').html(response);
});
}
//Invoke the function to get the word of the day
getWordOfTheDay();
</script>
More examples of using AJAX here - http://www.w3schools.com/ajax/ajax_examples.asp
More info about jQuery get method - https://api.jquery.com/jquery.get/
Also there are very good explanations of AJAX on stackoverflow here - How does AJAX work?

Use jQuery in external php file

I have a php file that I load into another php file with jQuery. This works, but the moment I start using jQuery in the 'external file', I get ERROR 500.
The reason I used this approach is because this is handy to refresh the data after an AJAX function.
This I have:
test.php:
<script type="text/javascript" src="js/modernizr.custom.29473.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function () {
$(document).tooltip({
items: ".plupic , .ingr",
content: function() {
var element = $( this );
if ( element.is( ".plupic " ) ) {
var src = element.attr('src');
return "<img src='" + src + "' style='max-height: 300px; max-width: 300px;'>";
}
if ( element.is( ".ingr" ) ) {
var txt = element.text();
return txt;
}
}
});
$('#kasticket').load('cart.php');
});
</script>
</head>
<body>
<div class="container">
<div id="kasticket"></div><!-- Load data with jQuery-->
cart.php:
I just do a select from the database and write some data to a table with echo();
This works perfectly, but the moment I want to use jQuery, I goes all wrong...(I know this for sure because the jQUery works in a local html file and putting this line in comment makes my php working again)
echo("
<script>
jQuery(document).ready(function() {
if($('#L$MyAant').width() < 70) {
$('.TR1$MyAant').show();
$('.TR2$MyAant').hide();
}else{
$('.TR2$MyAant').show();
$('.TR1$MyAant').hide();
}
});
</script>
");
I have no idea what I'm doing wrong.
If its any help: http://www.itreflex.be/TestAcc/test.php (with currently the jQuery line in comment).
And this is cart.php, exported to txt, it was to long to paste here.
hard to tell without the full source code but I have got a couple of ideas:
First Error 500 should be the HTTP code for internal server error, which basically means that the error lies on the server, then on the PHP side.
Could it be possible that you are mixing up PHP and jQuery on some of your other statements not posted here?
Second, you missed a single quote on your line
$('#kasticket').load(cart.php');
In your cart.php remove the brackets after echo ... For example
echo "<script>
jQuery(document).ready(function() {
if($('#L$MyAant').width() < 70) {
$('.TR1$MyAant').show();
$('.TR2$MyAant').hide();
}else{
$('.TR2$MyAant').show();
$('.TR1$MyAant').hide();
}
});
</script>";
Try this above line in your cart.php and see if that works.

Change value of PHP variable with AJAX

The PHP:
<?php
$mainView = "views/dashboardView.php";
?>
The HTML:
<div class="mainContent">
<?php include($mainView); ?>
</div>
I would like the click event of a button to change what view .mainContent shows and I believe AJAX can accomplish this but as yet have not been able to get it to work.
Any advice?
You would have to modify your PHP script to allow for this.
For example:
PHP:
if (isset($_POST['change']))
{
$mainView = $_POST['change'];
echo $mainView;
}
HTML & jQuery:
<button id="change">Change the var</button>
<script>
$("#change").click(function() {
$.post("file.php", {change: $(this).val()},
function (data)
{
$("#mainContent").html(data);
});
});
</script>
<script type="text/javascript>
function changePage(pageDest){
var xmlobject = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlobject.onreadystatechange = function (){
if(xmlobject.readyState == 4 && xmlobject.status == 200){
document.getElementById("mainContent").innerHTML = xmlobject.responseText;
}
else{
document.getElementById("mainContent").innerHTML = 'Loading...';
}
}
xmlobject.open("GET",pageDest,true);
xmlobject.send();
}
</script>
<div class="mainContent" id="mainContent">
Change this HTML
</div>
<div onmouseup="changePage('views/dashboardView.php')">Get dashboard view</div>
The parameter in the changePage function is the location of the page that you would like to place in your mainContent <div>
Does this help?
You cannot change the value of a PHP variable, as PHP is Server Side (done first), and JS is Client Side (done after Server Side).
Typically AJAX is used to repopulate an area of a web page, but that would suit your purpose. In the example below, ajax/test.php is the new file you want to include. Obviously change the path/name as you wish, and create that file.
I will add though, if you are repopulating a large chunk of your page, it will probably be just as quick to fully reload it.
$(function(){
$('.your-button-class').on('click', function(){
$.post('ajax/test.php', function(data) {
$('.mainContent').html(data);
});
});
});
Storing the View in the session, will keep the site displaying this view until the user closes the browser and ends the session, the session expires or they change the view again.
The include that sets mainView
<?php
session_start();
$mainView = "views/dashboardView.php"; // default
if(isset($_SESSION['mainView']))
{
$mainView =$_SESSION['mainView'];
}
?>
// the ajax script that sets the mainView
<?php
session_start();
$_SESSION['mainView']='views/'.$_GET['mainView'].'.php';
?>
the javascript link for ajax
ajaxURL='ajax.php?mainView=otherDasboard';
you may also want to check for empty session variable and that the file exists before setting it

Write to div as data streams in

Consider an AJAX call that writes to a div:
recent_req=$.post('result.php', { d: data }, function(returnData) {
$('#content').html(returnData);
});
The PHP script at result.php performs some functions that take time, about 5-20 seconds per step. I am using PHP's flush() function to get the info to the browser as soon as each step starts and ends, but how can I get the Javascript to write the data to the #content div as it comes in?
Thanks.
EDIT:
To clarify: Assume result.php looks like the following and due to constraints cannot be practically refactored:
<?php
echo "Starting...<br />";
flush();
longOperation();
echo "Done with first long operation.<br />";
flush();
anotherLongOperation();
echo "Done with another long operation.<br />";
flush();
?>
How might the AJAX be structured to call result.php such that the echo statements are appended to the #content div as they come in? Any solution with / without jQuery is welcome. Thanks!
There's a technique using an iframe which you could use to achieve this.
Similar to other suggestions involving frames but it doesn't involve sessions or polling or anything, and doesn't need you to display the iframe itself. It also has the benefit of running any code you want at any point in the process, in case you're doing something more sophisticated with your UI than just pushing text to a div (e.g. you could update a progress bar).
Basically, submit the form to a hidden iFrame then flush javascript to that frame, which interacts with functions in the iFrame's parent.
Like this:
HTML:
<form target="results" action="result.php" method="post">
<!-- your form -->
<input type="submit" value="Go" />
</form>
<iframe name="results" id="results" width="0" height="0" />
<div id="progress"></div>
Javascript, in your main page:
function updateProgress(progress) {
$("#progress").append("<div>" + progress + "</div>");
}
result.php:
<?php
echo "<script language='javascript'>parent.updateProgress('Starting...');</script>";
flush();
longOperation();
echo "<script language='javascript'>parent.updateProgress('Done with first long operation.');</script>";
flush();
anotherLongOperation();
echo "<script language='javascript'>parent.updateProgress('Done with another long operation.');</script>";
flush();
?>
You cannot 'stream' data using regular ajax calls, for you can't make your user's browser 'listen' to server requests. Your 'success' function will only be called when data's done processing.
There's, though, much discussion on 'Ajax Push' on the internet and apparently HTML5 has websocket objects that can be used to make your user's browser listen to server requests. The syntax definition is not quite stable yet, so you don't want to mess with it, as it may change soon.
What you may want to do is dispatch a request for step1, wait for its return and then dispatch a request for step2. It'll add some overhead to your overall processing time (and will make it much more verbose), but it should work fine if you only have a few big steps. If your steps don't take too much processing, you shouldn't do it (as the communication time will become greater than your 'effective processing time').
EDIT: What you can also do is write the progress on the user's session, for example. That way, you can periodically ping the server with a request for an update on the status. This way, even if you have many small steps, you'll only have to dispatch requests every 10 seconds or so, that being an improvement over dispatching for every step.
As an alternative solution, you could submit a hidden form into an iframe, as shown in the following example:
<?php
function output_data($data) {
echo str_pad($data, 4096, ' ', STR_PAD_RIGHT) . "\n";
flush();
}
function long_runner() {
output_data("");
output_data(date("H:i:s").' - Starting...<br />');
sleep(10);
output_data(date("H:i:s").' - Done with first long operation.<br />');
sleep(10);
output_data(date("H:i:s").' - Done with another long operation.<br />');
return("<script>parent.task_complete()</script>");
}
if (isset($_REQUEST["status"])) {
die(long_runner());
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Write to IFRAME as data streams in</title>
<style>
#myform { display: none }
#frm { width: 50% }
</style>
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function task_complete() {
alert('Task completed');
}
$(document).ready(function() {
$('#starter').click(function() {
$('#myform').submit();
});
});
</script>
</head>
<body>
<form id="myform" method="get" target="frm" action="<?= $_SERVER['SCRIPT_NAME'] ?>">
<input type="hidden" name="status" value="0">
</form>
Start<br />
<iframe id="frm" name="frm" frameborder="0"></iframe>
</body>
</html>
Writing a dynamic data stream to a div:
Here goes.. you asked specifically how to dynamically write data streams to a "div". As many have said it is possible to write dynamically to an iframe and we just need to go one step further. Here is a complete solution to your issue, which will bring that data back to your div with a maximum delay of .5 seconds. It can be adapted if you need a more prompt update.
<!DOCTYPE html>
<html>
<head>
<title>dynamic listener</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
var count;
$(function(){
$('#formx').submit(function(){
setTimeout(function(){ check_div(); }, 500);
count = 0;
return true;
});
});
function check_div()
{
var $iframetxt = $('#iframex').contents().text();
var $div = $('#dynamic');
if( $iframetxt != $div.text() )
{
console.log('rewritten!');
$div.text( $iframetxt );
setTimeout(function(){ check_div(); }, 500);
count = 0;
}
else
{
count++;
if(count < 40) setTimeout(function(){ check_div(); }, 500);
else console.log('timed out');
}
}
</script>
</head>
<body>
<div>
Form
<form id="formx" action="result.php" method="post" target="iframex">
<input type="submit" />
</form>
</div>
<div id="dynamic"></div>
<iframe id='iframex' name="iframex" style="display:none" ></iframe>
</body>
</html>
1. On form submit, the streaming data is sent to the iframe.
For this we just set the target attribute in the form tag to the iframe name.
2. check_div() runs every .5 seconds to compare the text of #dynamic div to the text contents of the iframe.
If there is a difference between them, the data is written to the div and the timeout is called again. If there is no difference, the timeout counter increments. If the count is less than 40 (40 x .5 sec = 20 seconds), it calls the timeout again. If not, we assume the stream has completed.
Here is a solution using polling with a session:
HTML:
<!DOCTYPE html>
<html>
<body>
<div id="content"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var pollTimeout;
function pollResult(){
$.get('poll.php', function(response) {
// Update #content with partial response
$('#content').html(response);
pollTimeout = setTimeout(pollResult, 1000);
});
}
$.post('result.php', function(response) {
// Result is loaded, stop polling and update content with final response
clearTimeout(pollTimeout);
$('#content').html(response);
});
// Start polling
pollResult();
</script>
</body>
</html>
Result PHP:
<?php
class SemiStream{
public function __construct(){
#session_start();
$_SESSION['semi_stream'] = '';
}
public function write($data){
#session_start();
$_SESSION['semi_stream'] .= $data;
// We have to save and close the session to be
// able to read the contents of it in poll.php
session_write_close();
}
public function close(){
echo $_SESSION['semi_stream'];
unset($_SESSION['semi_stream']);
}
}
$stream = new SemiStream();
$stream->write("Starting...<br />");
sleep(3);
$stream->write("Done with first long operation.<br />");
sleep(3);
$stream->write("Done with another long operation.<br />");
$stream->close();
echo 'Done.';
Poll PHP:
<?php
session_start();
echo $_SESSION['semi_stream'];
This works, without the use of PHP's output buffering.
Check out the Pusher service, seems like it could do exactly what you want: http://pusher.com/
Probably, the question is about how to implement Push technology in your app. I would suggest you to look this question which has great answer with example

php inside javascript checkbox value

I have a list list of checkbox with name of files that came froma DB. Then I have button for delete the files. I have the following code for the button:
<input type='button' id='submit_btn' onclick='eraseFile()' value='DELETE FILES' />
and the eraseFile function
...
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
<?php
echo "HElllo World";
?>
}
</script>
It gives an error "missing ; before statement" and "eraseFile is not defined"
Is it possible to write php inside javascript right??
Is it possible to write php inside javascript right??
Unless the PHP code is generating valid JavaScript, then no.
The reason eraseFile is being called undefined is that your echo statement is causing a syntax error since it is printing the string literal Hellllo World at the end of the JavaScript function which violates JavaScript syntax rules.
Yes, it is possible.
PHP is parsed on the server, so you will literally be printing "HElllo World" inside your javascript function, which would probably cause an error.
You might be looking do do the following:
<?php echo 'document.write("Hello World!");'; ?>
Your PHP output gets appended to your JS function making your javaascript look like this:
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
HElllo World //syntax error here
}
</script>
You can do this:
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
alert("<?php echo "HElllo World"; ?>");
}
</script>
This will give a pop-up saying 'Hello World'
To pass a value from your Javascript function to your PHP script, you can do this:
var yourJsVar = {assign value here};
url = "yourPHPScript.php?value=" + yourJsVar;
if (window.XMLHttpRequest)
{ // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = someFunction;
//someFunction will get called when the PHP script is done executing
try
{
req.open("GET", url, true);
}
catch (e)
{
alert(e);
}
req.send(null);
}
else if (window.ActiveXObject)
{ // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req)
{
req.onreadystatechange = someFunction;
req.open("GET", url, true);
req.send();
}
}
In your PHP script:
$yourPhpVar = $_GET['value'];
I mentioned someFunction above that gets called after the PHP script completes execution. This is how it should look. (Note that this is on your Javascript)
function someFunction()
{
if(req.readyState == 4 && req.status == 200)
{
//this will only execute after your AJAX call has completed.
//any output sent by your PHP script can be accessed here like this:
alert(req.responseText);
}
}
Try to echo a meaningful javascript code, "Hello World" it's not a valid JS statement.
Try something like
<?php
echo "alert('HElllo World');";
?>
Where is your eraseFile function defined?
if it is not defined until after the place it is called, you will get that error.
Side note:
You can have php echo inside of the javascript, except what you have there will not do much...
Yes, you can use PHP code in you script files, but your code generate invalid script code here.
<?php
echo "HElllo World"; // becomes: HElllo World (text!) in JS
?>
It is possible to write PHP in Javascript, but it is not the best pratice. The way we normaly do this is through AJAX read the documentation : http://api.jquery.com/category/ajax/
Yes, it is possible to include PHP inside JavaScript, since the PHP will be executed on the server before the page contents are sent to the client. However, in your case, what is sent is the following:
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
HElllo World
}
</script>
This doesn't validate as JavaScript, since the "Helllo World" is not a valid JavaScript command. This is why the function isn't being defined properly. You need to replace the "Helllo World" string with an actual JavaScript command.

Categories