tags:

views:

37

answers:

2

Hi all,

I got this prob. In a web page I have a DIV that display a counter ( a PHP variable, $count). I have also a JS function that change the INNERHTML property of the DIV. I'm not able to change the js var on the changing of the PHP one.

HTML

<DIV id="counter">0</DIV>

PHP

while (----) {
  do_something;
  $count++;
}

JS

function ChangeDiv() {
document.getElementById("counter").innerHTML = // here the value of $count;
}
setinterval("ChangeDiv()",3600);

I want to to refresh the DIV every sec inserting in it the value of $count... but doing

document.getElementById("counter").innerHTML = <?php echo($count); ?>;

is wrong 'cause it will output just the initial value of $count.

I tried to insert a parameter in the function ChangeDiv, but in that way I had to call the function every time $count changed, echoing a

echo("<script>ChangeDiv('".$count."');</script>");

...that's really not functional.

Someone knows a simpler way to do it??

+2  A: 

You need to use some sort of AJAX implementation to get this to work.

It will allow Js to query your PHP script to get a new value for $count

It looks like you might be writing some sort of progress bar?

jakenoble
A: 

Note that PHP runs on the server side and generates HTML / Javascript. Javascript runs on the client side.

What you would have to do to show a progress bar like that is to output <script> snippets that update your DIV element. If you put the line

document.getElementById("counter").innerHTML = "<?php echo($count); ?>";

(notice the quotes)

into the loop, and output buffering is turned off, and the counter HTML element was output before, you will get some sort of progress bar.

However, depending on what you want kind of action you are running behind that progress bar, an Ajax driven progress indicator may be much, much more elegant.

Pekka
My situation is this: in the while loop PHP script does a lot of calculations (it takes aprox. 20/30 secs), so before starting PHP script I output HTML (a page that should show time elapsed, operation done and percentage). I'd like to change HTML while PHP is still running. I'm not expert with AJAX...I've looked around and found many examples but no one cover my situation. Could you be so kind to give me some more tips or a link to something good for me. Thanks in advanceThanks in advance.
Nick
@Nick you should be nearly there then. Just put a full `<script>document.........etc. etc.</script>` into the loop so it gets output every x seconds, and run a `ob_flush()` directly after to make sure the generated code gets sent to the browser straight away.
Pekka