Progress bar AJAX and PHP

前端 未结 2 2063
长情又很酷
长情又很酷 2020-12-08 12:24

I want to create a progress bar for a server-side task ( written in php )

For learning purposes the example and task would be very simplistic. I would have a te

2条回答
  •  醉梦人生
    2020-12-08 13:13

    Not only one question in here

    Your question would be two:

    • How can I do AJAX calls to specific functions in PHP?
    • How can I do a progress bar with AJAX?

    How can I do AJAX calls to specific functions in PHP?

    Your AJAX code is fine. The only thing you have to do in your PHP is receive this call.

    Look at your request. You send a variable nr with your request:

    server_side.php?nr="+loop_index

    That will help us in the php code to determine that this is an AJAX call to do the sum operation. Now in the PHP:

    Thats it.

    How can I do a progress bar with AJAX?

    We need to make other AJAX call to request the progress to PHP.
    First, we do another AJAX call to retrieve the progress with a timer!

        var timer;
        
        //try to delete duplications. Do a generic function that does the request to php
        function makeRequest(toPHP, callback) {
            var xmlhttp;
            if (window.XMLHttpRequest)
              {// code for IE7+, Firefox, Chrome, Opera, Safari
              xmlhttp=new XMLHttpRequest();
              }
            else
              {// code for IE6, IE5
              xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
              }
            xmlhttp.onreadystatechange=function()
              {
                  if (xmlhttp.readyState==4 && xmlhttp.status==200)
                    {
                        callback(xmlhttp.response);
                    }
              }
            xmlhttp.open("GET",toPHP,true);
            xmlhttp.send();
         }
    
         function loop() {
             var loop_index = document.getElementById("loop_nr").value;
             makeRequest("server_side.php?nr="+loop_index, function(response) {
                 document.getElementById("sumDiv").innerHTML="Total sum = " + response;
                 clearInterval(timer);
             });
             timer=setInterval(makeRequest("getter.php", function(response) {
                 document.getElementById("percentageDiv").innerHTML=response;
              }),1000);
         }
    

    Then in the php side we retrieve this call as we did before and echo the $_SESSION['progress'] (as you already have)

    
    

    And that's it!

提交回复
热议问题