mercredi 31 janvier 2018

Laravel - Async Ajax Requests are blocked

I tried the whole day to get a problem with two ajax requests solved.

The purpose of my script is to start a process by an ajax call while another ajax call is getting the status/progress of this process.

My script is based on PHP Ajax Progress Bar.

I am using Laravel for this.

This my index view.

<!DOCTYPE html>
<html lang="">
<head>
    <meta name="csrf-token" content="">
</head>
<body>
<div id="progress"></div>
<div id="message"></div>

<!-- Scripts -->
<script src=""></script>
<script type="text/javascript">
    var timer;
    var index=0;

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    function refreshProgress() {
        $("#message").text("Refreshing...." + (index++)); //debug line
        $.ajax({
           url: "/status",
           async: true,
           success: function(data){
               $("#progress").html(data)
            if(data >= 100) {
                window.clearInterval(timer);
                timer= window.setInterval(completed, 1000);
            }},
            error: function (xhr, ajaxOptions, thrownError) {
               console.log(xhr.status);
                window.clearInterval(timer);
                timer= window.setInterval(completed, 1000);
            }
        });
    }

    function completed() {
        window.clearInterval(timer);
    }

    $(document).ready(function() {
        $.ajax({url: "/start", async: true});
        timer= window.setInterval(refreshProgress, 1000);
    });

</script>
</body>
</html>

After the document is loaded the url start is called by an ajax request.

Every second another ajax call is initiated to call the url status.

Inside the controller nothing special is happening.

public function start(Request $request) {

        Log::info("Start....");

        foreach(range(0, 20) as $number) {

            sleep(1);

        }
    }

    public function status(Request $request) {

        return json_encode(112);
    }

The start method is running a loop, while the status method is simply returning a number.

I liked to prevent anything that might block the process like this Solving Concurrent Request Blocking in PHP.

But what I see in my browser is that after the start URL is called all requests to status are queued. As soon as the start method finished all status requests are processed.

I am not able to get the result of the status request while the start method is running.

Pending network traffic

I am not getting the problem. What did I missed?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire