Search code examples
javascriptphplamp

How to update web page multiple times as server-side task progresses?


I would like to create a page that will allow the IT guys to select some servers from a list and an operation to perform on the them and then click go. Then have the textarea on the page update with the status of each operation as it completes. Each server maintenance task can take a minute or two. They would like to see updates on the page as each server completes the selected task.

Not sure which technologies to use on the front-end. The back-end is not a problem at all. I can easily take the full list of servers, perform the operation on each server then return the full list, with the result from each server. However, no one wants to wait for all the servers to complete before getting updates.

Normally I would use ajax to update a portion of a page but that is just for a single call/response. I think if I use a javascript loop to call a php script via ajax for each server, then the javascript loop will block the UI updates until the javascript function completes.

Any ideas?


Solution

  • Jquery has a method to perform an asynchronous HTTP Ajax request (http://api.jquery.com/jquery.ajax). Create a recursive javascript function to make the ajax call. Once you get the list of servers and desired operation selected by the user on the UI, call the RecursiveAjax function. With each result, call another function to update the UI.

    function RecursiveAjax(serverArray, currentIndex, operation)
    {
      var operationResult = "";
      $.ajax({
             type: "GET"
             url:  "ServerOperation.php",
             data: {Operation: operation, Server: serverArray[currentIndex]},
             success: function (result) {
                 operationResult = JSON.stringify(result);
                 UpdateUI(operationResult);
             }
         });
         var nextIndex = currentIndex + 1;
         if(nextIndex < serverArray.length) {
           RecursiveAjax(serverArray, nextIndex, operation);
         }
    }