Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Ajax Loading image

Tags:

jquery

ajax

I would like to implement a loading image for my jquery ajax code (this is when the jquery is still processing) below is my code:

$.ajax({     type: "GET",     url: surl,     dataType: "jsonp",     cache : false,     jsonp : "onJSONPLoad",     jsonpCallback: "newarticlescallback",     crossDomain: "true",     success: function(response) {         alert("Success");     },     error: function (xhr, status) {          alert('Unknown error ' + status);     }    }); 

How can I implement a loading image in this code. Thanks

like image 437
Kern Elliott Avatar asked Jan 06 '12 17:01

Kern Elliott


2 Answers

Description

You should do this using jQuery.ajaxStart and jQuery.ajaxStop.

  1. Create a div with your image
  2. Make it visible in jQuery.ajaxStart
  3. Hide it in jQuery.ajaxStop

Sample

<div id="loading" style="display:none">Your Image</div>  <script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script> <script>     $(function () {         var loading = $("#loading");         $(document).ajaxStart(function () {             loading.show();         });          $(document).ajaxStop(function () {             loading.hide();         });          $("#startAjaxRequest").click(function () {             $.ajax({                 url: "http://www.google.com",                 // ...              });         });     }); </script>  <button id="startAjaxRequest">Start</button> 

More Information

  • jQuery.ajaxStart()
  • jQuery.ajaxStop()
like image 146
dknaack Avatar answered Sep 25 '22 19:09

dknaack


Try something like this:

<div id="LoadingImage" style="display: none">   <img src="" /> </div>  <script>   function ajaxCall(){     $("#LoadingImage").show();       $.ajax({          type: "GET",          url: surl,          dataType: "jsonp",          cache : false,          jsonp : "onJSONPLoad",          jsonpCallback: "newarticlescallback",          crossDomain: "true",          success: function(response) {            $("#LoadingImage").hide();           alert("Success");          },          error: function (xhr, status) {             $("#LoadingImage").hide();           alert('Unknown error ' + status);          }           });       } </script> 
like image 44
Per Kastman Avatar answered Sep 25 '22 19:09

Per Kastman