How to show progress bar while loading, using ajax

JavascriptPhpJqueryAjax

Javascript Problem Overview


I have a dropdown box. When the user selects a value from the dropdown box, it performs a query to retrieve the data from the database, and shows the results in the front end using ajax. It takes a little bit of time, so during this time, I want to show a progress bar. I have searched, and I have found numerous tutorials on creating progress bars for uploads, but I haven't liked any. Can anybody provides some helpful guidance for me?

My ajax code:

<script>
$(function() {
    $("#client").on("change", function() {
      var clientid=$("#client").val();
     
        $.ajax({
            type:"post",
            url:"clientnetworkpricelist/yourfile.php",
            data:"title="+clientid,
            success:function(data){
             $("#result").html(data);
            }
        });

    });
});
</script>

Javascript Solutions


Solution 1 - Javascript

This link describes how you can add a progress event listener to the xhr object using jquery.

$.ajax({
    xhr: function() {
        var xhr = new window.XMLHttpRequest();

        // Upload progress
        xhr.upload.addEventListener("progress", function(evt){
            if (evt.lengthComputable) {
                var percentComplete = evt.loaded / evt.total;
                //Do something with upload progress
                console.log(percentComplete);
            }
       }, false);
       
       // Download progress
       xhr.addEventListener("progress", function(evt){
           if (evt.lengthComputable) {
               var percentComplete = evt.loaded / evt.total;
               // Do something with download progress
               console.log(percentComplete);
           }
       }, false);
       
       return xhr;
    },
    type: 'POST',
    url: "/",
    data: {},
    success: function(data){
        // Do something success-ish
    }
});

Solution 2 - Javascript

<script>
$(function() {
    $("#client").on("change", function() {
      var clientid=$("#client").val();
     //show the loading div here
    $.ajax({
            type:"post",
            url:"clientnetworkpricelist/yourfile.php",
        data:"title="+clientid,
        success:function(data){
             $("#result").html(data);
          //hide the loading div here
        }
    }); 
    });
});
</script>

Or you can also do this:

$(document).ajaxStart(function() {
        // show loader on start
        $("#loader").css("display","block");
    }).ajaxSuccess(function() {
        // hide loader on success
        $("#loader").css("display","none");
    });

Solution 3 - Javascript

Basically you need to have loading image Download free one from here http://www.ajaxload.info/

$(function() {
    $("#client").on("change", function() {
      var clientid=$("#client").val();
      $('#loadingmessage').show();

    $.ajax({
            type:"post",
            url:"clientnetworkpricelist/yourfile.php",
        data:"title="+clientid,
        success:function(data){
             $('#loadingmessage').hide();
             $("#result").html(data);
        }
    }); 
    });
});

On html body

<div id='loadingmessage' style='display:none'>
	   <img src='img/ajax-loader.gif'/>
</div>

Probably this could help you

Solution 4 - Javascript

Here is an example that's working for me with MVC and Javascript in the Razor. The first function calls an action via ajax on my controller and passes two parameters.

        function redirectToAction(var1, var2)
        {
            try{

                var url = '../actionnameinsamecontroller/' + routeId;

                $.ajax({
                    type: "GET",
                    url: url,
                    data: { param1: var1, param2: var2 },
                    dataType: 'html',
                    success: function(){
                    },
                    error: function(xhr, ajaxOptions, thrownError){
                        alert(error);
                    }
                });

            }
            catch(err)
            {
                alert(err.message);
            }
        }

Use the ajaxStart to start your progress bar code.

           $(document).ajaxStart(function(){
            try
            {
                // showing a modal
                $("#progressDialog").modal();

                var i = 0;
                var timeout = 750;

                (function progressbar()
                {
                    i++;
                    if(i < 1000)
                    {
                        // some code to make the progress bar move in a loop with a timeout to 
                        // control the speed of the bar
                        iterateProgressBar();
                        setTimeout(progressbar, timeout);
                    }
                }
                )();
            }
            catch(err)
            {
                alert(err.message);
            }
        });

When the process completes close the progress bar

        $(document).ajaxStop(function(){
            // hide the progress bar
            $("#progressDialog").modal('hide');
        });

Solution 5 - Javascript

$(document).ready(function () { 
 $(document).ajaxStart(function () {
        $('#wait').show();
    });
    $(document).ajaxStop(function () {
        $('#wait').hide();
    });
    $(document).ajaxError(function () {
        $('#wait').hide();
    });   
});

<div id="wait" style="display: none; width: 100%; height: 100%; top: 100px; left: 0px; position: fixed; z-index: 10000; text-align: center;">
            <img src="../images/loading_blue2.gif" width="45" height="45" alt="Loading..." style="position: fixed; top: 50%; left: 50%;" />
</div>

Solution 6 - Javascript

After much searching a way to show a progress bar just to make the most elegant charging could not find any way that would serve my purpose. Check the actual status of the request showed demaziado complex and sometimes snippets not then worked created a very simple way but it gives me the experience seeking (or almost), follows the code:

$.ajax({
    type : 'GET',
    url : url,
    dataType: 'html',
    timeout: 10000,
    beforeSend: function(){
	    $('.my-box').html('<div class="progress"><div class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div></div>');
	    $('.progress-bar').animate({width: "30%"}, 100);
    },
    success: function(data){  
	    if(data == 'Unauthorized.'){
            location.href = 'logout';
        }else{
    	    $('.progress-bar').animate({width: "100%"}, 100);
    	    setTimeout(function(){
    		    $('.progress-bar').css({width: "100%"});
    		    setTimeout(function(){
				    $('.my-box').html(data);
    		    }, 100);
    	    }, 500);
        }
    },
    error: function(request, status, err) {
        alert((status == "timeout") ? "Timeout" : "error: " + request + status + err);
    }
});

Solution 7 - Javascript

I know that are already many answers written for this solution however I want to show another javascript method (dependent on JQuery) in which you simply need to include ONLY a single JS File without any dependency on CSS or Gif Images in your code and that will take care of all progress bar related animations that happens during Ajax Request. You need to simnply pass javascript function like this

var objGlobalEvent = new RegisterGlobalEvents(true, "");

Preview of Fiddle Loader Type

Here is the working fiddle for the code. https://jsfiddle.net/vibs2006/c7wukc41/3/

Solution 8 - Javascript

I did it like this

CSS

html {
    -webkit-transition: background-color 1s;
    transition: background-color 1s;
}
html, body {
    /* For the loading indicator to be vertically centered ensure */
    /* the html and body elements take up the full viewport */
    min-height: 100%;
}
html.loading {
    /* Replace #333 with the background-color of your choice */
    /* Replace loading.gif with the loading image of your choice */
    background: #333 url('/Images/loading.gif') no-repeat 50% 50%;

    /* Ensures that the transition only runs in one direction */
    -webkit-transition: background-color 0;
    transition: background-color 0;
}
body {
    -webkit-transition: opacity 1s ease-in;
    transition: opacity 1s ease-in;
}
html.loading body {
    /* Make the contents of the body opaque during loading */
    opacity: 0;

    /* Ensures that the transition only runs in one direction */
    -webkit-transition: opacity 0;
    transition: opacity 0;
}

JS

$(document).ready(function () {
   $(document).ajaxStart(function () {     
       $("html").addClass("loading");
    });
    $(document).ajaxStop(function () {        
        $("html").removeClass("loading");
    });
    $(document).ajaxError(function () {       
        $("html").removeClass("loading");
    }); 
});

Solution 9 - Javascript

try this it may help you

 $.ajax({
  type:"post",
            url:"clientnetworkpricelist/yourfile.php",
        data:"title="+clientid,
  beforeSend: function(  ) {
    // load your loading fiel here
  }
})
  .done(function( data ) {
    //hide your loading file here
  });

Solution 10 - Javascript

I usually use this way simple and useful

<input id="datainput" type="text">
<div id="result"></div>
<button id="examplebutton"></button>
<script>
	$("#examplebutton").click(function(){
		let data=$("#datainput").val(); 
		$("#result").html("Please Wait..");  // it starts working when the button is clicked
		
		$.ajax({
			url:"../ajax/xyz.php",
			type:"POST",
			data:{data:data},
			success:function(result)
			{
				$("#result").html(result);  // When the data comes, the text will be deleted and the data will come.
			}
		});
	});
</script>

Solution 11 - Javascript

Well this will definitely work.
Here we go...

function yourFunction(){
	
	setTimeout(function(){
		$('#loading').show();
		
		setTimeout(function(){
			//your ajax code goes here...
			$('#loading').hide();			
		}, 500);

	}, 300);
}    

You can set css to your progress bar according to your requirement. Hide this div by default.

<div id="loading">
	<img id="loading-image" src="img-src" alt="Loading..." />
</div>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionXaviView Question on Stackoverflow
Solution 1 - JavascriptPrateekView Answer on Stackoverflow
Solution 2 - JavascriptSuvash sarkerView Answer on Stackoverflow
Solution 3 - JavascriptAnishView Answer on Stackoverflow
Solution 4 - JavascriptchuckView Answer on Stackoverflow
Solution 5 - JavascriptRohit DodiyaView Answer on Stackoverflow
Solution 6 - JavascriptGabriel GlauberView Answer on Stackoverflow
Solution 7 - Javascriptvibs2006View Answer on Stackoverflow
Solution 8 - JavascriptNoWarView Answer on Stackoverflow
Solution 9 - JavascriptAliView Answer on Stackoverflow
Solution 10 - JavascriptBurak KömürcüView Answer on Stackoverflow
Solution 11 - JavascriptMaitry GohilView Answer on Stackoverflow