Reputation: 1659
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
Upvotes: 36
Views: 151977
Reputation: 4504
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>
Upvotes: 53
Reputation: 60466
You should do this using jQuery.ajaxStart
and jQuery.ajaxStop
.
jQuery.ajaxStart
jQuery.ajaxStop
<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>
Upvotes: 55
Reputation: 143
Its a bit late but if you don't want to use a div specifically, I usually do it like this...
var ajax_image = "<img src='/images/Loading.gif' alt='Loading...' />";
$('#ReplaceDiv').html(ajax_image);
ReplaceDiv is the div that the Ajax inserts too. So when it arrives, the image is replaced.
Upvotes: 3
Reputation: 31
Please note that: ajaxStart / ajaxStop is not working for ajax jsonp request (ajax json request is ok)
I am using jquery 1.7.2 while writing this.
here is one of the reference I found: http://bugs.jquery.com/ticket/8338
Upvotes: 2