1

I have following two files and want to get data from php and recieve it in javascript file.

1) PHP file:

<?php
    $i;
    for($i = 0; $i < 1000; $i++) {
        echo $i;
    }
?>

2) JavaScript file:

<script>
    var j = -1; 
    var xhttp = new XMLHttpRequest();

    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            j = this.responseText;
        }
    };

    xhttp.open("GET", "www.mywebsite.com/php_file.php", true);

    while(j < 999) {
        xhttp.send();
        document.getElementById("demo").innerHTML = j;
    }
</script>

Now, the problem is, when run my java script it return me the final value of 'i', but i want to retrieve every value of 'i' while it is in for-loop, like from 0 to 999.. but it return only when php file fully executes it self

4
  • This should be in forloop echo $j; Commented May 20, 2017 at 13:10
  • ricky its different.. it was not used within for loop.. @sahil i did that too but no its not working still getting the final value Commented May 20, 2017 at 13:52
  • try using flush();ob_flush(); after echo $i; you need to flush your buffer after printing your each i value. Commented May 20, 2017 at 14:11
  • i did but its not useful.. same output Commented May 20, 2017 at 14:11

1 Answer 1

1

Change your php file as follows : you are outputting j outside of loop

<?php
  $i;
  $j = 0;
 for($i = 0; $i < 1000; $i++){
     $j = $i * $i;
     echo $j;
 } ?>
Sign up to request clarification or add additional context in comments.

3 Comments

no its not working.. it return the final echo output... means it return output when whole php executes.
So, it is problem in js itself . I think the best will be to use ajax.
i am using ajax in my javascript

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.