What
What

Reputation: 157

Javascript in while loop not changing anything until the loop finished

I have 2 seperate files.

The iframe executes the changePercent command in the parent window, but it doesn't change the number instantly, it is only changed after the loop finished. Is there any way to fix this? Need this for a progress bar thingy.

Thanks in advance!

This is the file I open in my browser

<span id="test">1</span><br />
<iframe src="script.php?league=Nemesis"></iframe>

<script type="text/javascript">
function changePercent(val) {
    document.getElementById("test").innerHTML=val;
}
</script>

This is the embedded iframe

<?php set_time_limit(0);
include('../assets/includes/functions.inc.php'); ?>
<?php
$i = 0;
$step = 200;
$end = 15000 - $step;
$league = $_GET['league'];
$found = false;
$status = false;

while ($found == false && $i < $end) {
    if($i < $end) { $i = $i + $step; }
    $ladder = file_get_contents("http://api.pathofexile.com/ladders/".$league."?limit=".$step."&offset=".$i);

    $ladder = str_replace('"online":false', '"online":"no"', $ladder);
    $ladder = str_replace('"online":true', '"online":"yes"', $ladder);

    $json = json_decode($ladder, true);
    foreach ($json['entries'] as $address) {
        if($address['online'] = "yes") {
            $status = true;
            // do something
        }
    }

    ?>
    <script type="text/javascript">
        parent.changePercent('<?php echo $i ?>');
    </script>
    <?php
}
?>

Upvotes: 1

Views: 217

Answers (2)

Dima
Dima

Reputation: 8652

php is a server side language. when the php runs the while loop, that means the browser is still waiting for page data, and it will be sent to the browser only when the php is finished. in your changePercent you have a php code that is located AFTER the while loop, so it will run the while loop before it can evaluate the php inside the changePercent

so there is no "fix", you should just learn the basics of web programming

Upvotes: 2

Loothelion
Loothelion

Reputation: 379

You're exiting out of the PHP loop when you use ?> try the following code segment.

echo '<script type="text/javascript"> parent.changePercent(' .  $i .'); </script>';

This will tell PHP to print out that line for each time your loop executes through.

Upvotes: 0

Related Questions