Real-Time Progress Tracking with AJAX

Back-End

using System.Threading;
using System.Web.Http;
using System.Web.Mvc; // For JsonResult


public class ProgressController : ApiController
{
    [HttpPost]
    [Route("api/progress/start-task")]
    public JsonResult StartTask()
    {
        int totalSteps = 100;


        for (int i = 1; i <= totalSteps; i++)
        {
            // Simulate some work (e.g., 100ms per step)
            Thread.Sleep(100);


            // Return progress to the client
            HttpContext.Current.Response.Headers["X-Progress"] = $"{i * 100 / totalSteps}%";
            var progress = new { Progress = i * 100 / totalSteps };
            HttpContext.Current.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(progress));
            HttpContext.Current.Response.Flush();
        }


        return new JsonResult
        {
            Data = new { Message = "Task Completed", Progress = 100 },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
    }
}


Front-End

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX Progress Bar in .NET Framework</title>
    <style>
        #progress-bar {
            width: 100%;
            background-color: #f3f3f3;
        }
        #progress-bar-fill {
            width: 0%;
            height: 30px;
            background-color: #4caf50;
            text-align: center;
            line-height: 30px;
            color: white;
        }
    </style>
</head>
<body>
    <h1>AJAX with Progress Bar in .NET Framework</h1>
    <button id="start-btn">Start Task</button>
    <div id="progress-bar">
        <div id="progress-bar-fill">0%</div>
    </div>


    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#start-btn').click(function () {
                $('#progress-bar-fill').css('width', '0%').text('0%');


                $.ajax({
                    url: '/api/progress/start-task',
                    type: 'POST',
                    xhr: function () {
                        var xhr = new window.XMLHttpRequest();


                        // Event to capture progress
                        xhr.onprogress = function (e) {
                            var progressText = e.target.responseText.trim().split('\n').pop();
                            try {
                                var progressData = JSON.parse(progressText);
                                $('#progress-bar-fill').css('width', progressData.Progress + '%').text(progressData.Progress + '%');
                            } catch (error) {
                                console.log('Progress parsing error', error);
                            }
                        };


                        return xhr;
                    },
                    success: function (data) {
                        $('#progress-bar-fill').css('width', '100%').text('100%');
                        alert(data.Message); // Notify the user that the task is complete
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert('Error: ' + textStatus);
                    }
                });
            });
        });
    </script>
</body>
</html>