Skip to content
Advertisement

Ajax Status Pending On Multiple Requests

I want to create a jQuery Progress Listener.

I have a button which on click executes a PHP script, which runs through a bunch of functions and foreach loops and it takes a while to load.

I want to get a response on each loop using the XMLHttpRequest(). I am using this youtube video as a reference. But the scripts are not working well.

When I opened The Chrome Developer Tools on the Network Tab, the request checkprogress.php is sent but the response is “pending” until the scripts finish the load, and then it responds with 100% all of a sudden .

Below is the code for each file

checkprogress.php

<?php

$file = "progress.txt";
$data = file_get_contents($file);
echo $data;
?>

Index.php

<style type="text/css">
    #container{
        width: 300px;
        height: 20px;
        border: solid thin #aaa;
    }
    #progress{
        background-color: lightblue;
        height: 100%;
        width: 100%;
        color: grey;
        text-align: center;
    }
</style>

<div id="container"><div id="progress">0%</div></div>
<button id="start" onclick="begin(event)">Start</button>

<script type="text/javascript">

    var prog = document.getElementById('progress');
    var button = document.getElementById('start');

    function begin(event){

        xhr = new XMLHttpRequest();
        
        xhr.open("POST", "script.php", true);
        
        xhr.onload = function(){
            
            if(xhr.status === 200){
                alert(xhr.responseText);
                clearInterval(timer);
            }

        }
        
        timer = setInterval(checkProgress, 100);
        xhr.send();
    }

    function checkProgress(event){

        xhr2 = new XMLHttpRequest();
        
        xhr2.open("POST", "checkprogress.php", true);
        
        xhr2.onload = function(){
            
            if(xhr2.status === 200){

                prog.style.width = xhr2.responseText + "%";
                prog.innerHTML = xhr2.responseText + "%";
            }

        }
        xhr2.send();
    }
</script>

Script.php

<?php

$file = "progress.txt";
for($i = 1; $i<= 10; $i++){
    
    sleep(1);
    file_put_contents($file, ($i * 10));

}
echo "done";
?>

How can I fix this?

Advertisement

Answer

As said above in the comment ajax sends 1 request and get only response when the php script finishes so there is no way to do that.

I was developing wordpress plugin and am new to this so the way around it as that if i am using PHP OOP and wordpress i just need to send the request through wp_ajax hook and run the methods one after another and each method must send response to ajax file and then send another request with the response data to the next method until i reach the final confirmation that’s all if someone needs it I will share the code

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement