0

I am trying to load php file's output in html div. And I have tried it with jQuery's ($('div').load(url_here)) method and it's working fine, but my php file is as below:

<?php
for( $i = 0 ; $i < 10 ; $i++ )
{
    echo date('h:i:s').'<br>';
    //flush the output buffer
    flush();
    //send the output buffer
    ob_flush();
   //sleep here
    sleep(1);
} ?>

Now this php file prints a single line every second, but when I load this php in html's div, it takes 10 seconds once the page is loaded and then adds 10 lines all together. I want to load div as php file returns a single line every second. I mean, I want html to respond same as php (i.e. load one line every second, so at 1st second it should load 1st line, at 2nd second it should add 2nd line and so on). So, is it possible? (P.S - I am beginner for this dynamic web)

2
  • You should learn something about ajax Commented Sep 23, 2014 at 16:56
  • What you want to do is not possible without javascript. Commented Sep 23, 2014 at 16:56

2 Answers 2

1

In order to get the result in every minute, you have to open an ajax request every minute to control the time in javascript, not in php.

Try:

var timer = window.setInterval(function()
{
    $('div').load(url_here); 
}, 1000);

And remove the for loop and the sleep() in php.

UPDATE:

To keep the history of the results, try this out:

var content = $('div').text();
$('div').load(url_here).append(content);
Sign up to request clarification or add additional context in comments.

3 Comments

can't vote up (don't have 15 reputations yet).But your both solutions worked. Just a question, these both solutions gives same output that replaces same line again and again, is it possible to have new results in new lines?
@JigarPatel don't worry about the vote, dude. I'm glad this helped you. See my update for your last question.
This worked ! Gret @DontVoteMeDown, Simple yet useful logic :D
0

PHP

   <?php

        echo date('h:i:s').'<br>';

    ?>

And JS

<script>

var timer_php = setInterval(function(){
$("#anydiv").load("abovefile.php");
},1000);

setTimeout(function(){
clearTimer(timer_php);
},10000);
</script>

3 Comments

Thats what the user want i guess, He wants the php to load after every 1 sec till 10 seconds
Yeah, now I can see your full code. Adding some explanation for the OP would be helpful.
your solution worked well..and @DontVoteMeDown's solution worked well too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.