Display jQuery Ajax Progress using Bootstrap Progress Bar Tutorial

Introduction

In this tutorial, I will teach you how to Display jQuery's AJAX Progress using the Bootstrap Progress Bar. This tutorial aims to provide IT/CS students or those new programmers with a reference and guide to learn to enhance their JavaScript programming capabilities. Here, snippets with some explanation will be provided. This can give them another knowledge on how they can provide a better web application for their end-users.

What is AJAX?

AJAX stands for Asynchronous JavaScript And XML. AJAX enables asynchronous updating of web pages by quietly sharing data with a web server. This indicates that a web page can be updated in sections without requiring a page reload. With the use of XML, HTML, CSS, and JavaScript, AJAX enables the creation of more effective, quick, and interactive online applications.

What is Bootstrap Progress?

Bootstrap Progress is one of the components of the Bootstrap Framework. It is built using two HTML elements, a width setting in CSS, and a few attributes. Visit the Bootstrap Official Website to know more about this content.

How to Display jQuery's AJAX Progress using Bootstrap Progress Bar?

This web application feature can be achieved with a few lines of JavaScript codes or scripts. Using the XHR setting option of jQuery's Ajax, we can capture the upload and download progress of the request. Here's an example snippet.

  1. $.ajax({
  2. xhr: function(){
  3. var xhr = $.ajaxSettings.xhr();
  4.  
  5. // Upload Progress
  6. xhr.upload.addEventListener('progress', function(e){
  7. if(e.lengthComputable){
  8. var completed = e.loaded/e.total;
  9. console.log("Upload Progress:", completed)
  10. }
  11. }, false)
  12.  
  13. // Download Progress
  14. xhr.addEventListener('progress', function(e){
  15. if(e.lengthComputable){
  16. var completed = e.loaded/e.total;
  17. var perc = Math.floor(completed * 100);
  18. console.log("Download Progress:", completed)
  19. }
  20. }, false)
  21.  
  22. return xhr;
  23. },
  24. })

Using the above script you can now update your Bootrstrap's progress bar. You can update your progress width and CSS using some JavaScript or jQuery methods. Below is an example of updating your progress bar.

  1. // Updating the Progress Bar Label
  2. $('#progressBar').text(completedPercentage+'%');
  3.  
  4. // Updating the Progress Bar Filled width
  5. $('#progressBar').css('width',completedPercentage+'%');

Example

Below is a simple web application that demonstrates our main goal for this tutorial. The application was written in HTML, CSS, JS, and PHP. It uploads an image or video and stores it on the server. The progress will start each time the user uploads a video or an image file to the given file input field. The progress bar will be shown above the input.

Interface

The below script holds the HTML and PHP Scripts of the application that display the elements or shows the application's user interface. It contains the form for uploading the file and the progress bar.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>JS Ajax Progress</title>
  8. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  9. <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
  10. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-IDwe1+LCz02ROU9k972gdyvl+AESN10+x7tBKgc9I5HFtuNz0wWnPclzo6p9vxnk" crossorigin="anonymous"></script>
  11. <style>
  12. html, body{
  13. min-height:calc(100%);
  14. width: calc(100%);
  15. }
  16. body{
  17. min-height: 100vh;
  18. width: 100vw;
  19. display: flex;
  20. flex-direction: column;
  21. align-items: center;
  22. justify-content: center;
  23. }
  24. </style>
  25. </head>
  26. <body class="bg-light bg-gradient">
  27. <div class="container-fluid w-100">
  28. <h1 class="text-center fw-bolder my-4">Displaying the Ajax Progress using Bootstrap Progress Bar</h1>
  29. <div class="d-flex justify-content-center">
  30. <hr class="col-4">
  31. </div>
  32. <div class="card rounded-0 shadow col-lg-5 col-md-7 col-sm-12 mx-auto">
  33. <div class="card-body">
  34. <div class="container-fluid">
  35. <form action="" id="sample-form">
  36. <div class="mb-3 d-none" id="progress-holder">
  37. <div class="progress">
  38. <div class="progress-bar" id="progress_bar" role="progressbar" aria-label="Example with label" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div>
  39. </div>
  40.  
  41. </div>
  42. <div class="mb-3">
  43. <label for="formFile" class="form-label">Choose Image</label>
  44. <input class="form-control" type="file" accept="image/*, video/*" name="upload" id="formFile" required>
  45. </div>
  46. </form>
  47. </div>
  48. <table class="table table-striped table-bordered">
  49. <colgroup>
  50. <col width="20%">
  51. <col width="80%">
  52. </colgroup>
  53. <thead>
  54. <tr class="bg-primary text-light">
  55. <th class="text-center">#</th>
  56. <th class="text-center">Filename</th>
  57. </tr>
  58. </thead>
  59. <tbody>
  60. <?php
  61. $dir = "uploads/";
  62. if(is_dir($dir)):
  63. $scandr = scandir($dir);
  64. $i = 1;
  65. foreach($scandr as $file):
  66. if(in_array($file, ['.', '..']))
  67. continue;
  68. ?>
  69. <tr>
  70. <th class="text-center"><?= $i++ ?></th>
  71. <td><a href="<?= $dir.$file ?>" target="_blank"><?= $file ?></a></td>
  72. </tr>
  73. <?php endforeach; ?>
  74. <?php endif; ?>
  75. </tbody>
  76. </table>
  77. </div>
  78. </div>
  79. </div>
  80. </body>
  81.  
  82. <script src="./app.js"></script>
  83. </html>

Creating JS Script

Here is the JavaScript code that executes jQuery's Ajax Request. The request will be triggered when the file input field detects any changes. This file is included or loaded at the interface page script.

app.js

  1. $(document).ready(function(){
  2. $('#formFile').change(function(){
  3. var inpFile = $(this).clone()
  4. var newForm = new FormData();
  5. newForm.append('uploaded', inpFile[0].files[0])
  6. // return false
  7. // newForm.append('uploaded', inpFile[0].files[0])
  8. $('#progress-holder').removeClass('d-none')
  9. var progressBar = $('#progress_bar');
  10. progressBar.text('0%');
  11. progressBar.attr('aria-valuenow',0);
  12. progressBar.css('width',0);
  13. $.ajax({
  14. url:"upload.php",
  15. data:newForm,
  16. method:'POST',
  17. type:"POST",
  18. processData:false,
  19. contentType:false,
  20. dataType:'JSON',
  21. error: err=>{
  22. console.error(err)
  23. alert("error")
  24. },
  25. xhr: function(){
  26. var xhr = $.ajaxSettings.xhr();
  27.  
  28. xhr.upload.addEventListener('progress', function(e){
  29. if(e.lengthComputable){
  30. var completed = e.loaded/e.total;
  31. var perc = Math.floor(completed * 100);
  32. console.log("Upload:", perc)
  33. progressBar.text(perc+'%');
  34. progressBar.attr('aria-valuenow',perc);
  35. progressBar.css('width',perc+'%');
  36. }
  37. }, false)
  38.  
  39. xhr.addEventListener('progress', function(e){
  40. if(e.lengthComputable){
  41. var completed = e.loaded/e.total;
  42. var perc = Math.floor(completed * 100);
  43. console.log("Download:",perc)
  44. progressBar.text(perc+'%');
  45. progressBar.attr('aria-valuenow',perc);
  46. progressBar.css('width',perc+'%');
  47. }
  48. }, false)
  49. return xhr;
  50. },
  51. success:function(response){
  52. var MyInterval = setInterval(function(){
  53. console.log("progress now:", progressBar.attr('aria-valuenow'))
  54. if(progressBar.attr('aria-valuenow') == 100){
  55. if(response.status == 'success'){
  56. console.log("Uploaded Filename:", response.filename)
  57. alert("File has been uploaded successfully")
  58. }else{
  59. alert(response.error)
  60. }
  61. clearInterval(MyInterval);
  62. location.reload()
  63. }
  64. },1000)
  65. }
  66. })
  67. })
  68. })

Creating the API

Here are the PHP Scripts that handle or store the uploaded file. The script creates the upload directory if not existed yet. It returns JSON data to validate if the file was uploaded successfully or not.

upload.php

  1. <?php
  2.  
  3. $dir = "uploads/";
  4. if(!is_dir($dir)){
  5. mkdir($dir);
  6. }
  7.  
  8. if(isset($_FILES['uploaded']) && !empty($_FILES['uploaded']['tmp_name'])){
  9. $fname = $_FILES['uploaded']['name'];
  10. $i = 0;
  11. while(true){
  12. $tmp_name = $dir.($i > 0 ? $i."_" :'').$fname;
  13. if(is_file($tmp_name)){
  14. $i++;
  15. }else{
  16. $fname = $tmp_name;
  17. break;
  18. }
  19. }
  20. $upload = move_uploaded_file($_FILES['uploaded']['tmp_name'], $fname);
  21. if($upload){
  22. echo json_encode(['status' => 'success', 'filename' => $fname]);
  23. }else{
  24. echo json_encode(['status' => 'failed', 'error' => "failed to upload"]);
  25. }
  26. }
  27. ?>

That's it! The complete source code file of the above example application is also provided on this website and is free to download. Feel free to download and modify it to do more experiments. The download button is located below this article.

Snaphot

Here is the snapshot of the result of the example web application

JS Display Ajax Progres

DEMO VIDEO

That's the end of this tutorial. I hope this Displaying Ajax Progress using Bootstrap Progress Bar Tutorial helps you with what you are looking for and that you'll find this useful for your current and future web application projects.

Explore more on this website for more Tutorials and Free Source Codes.

Comments

Add new comment