Track/Log ajax request states
by Venkata Panga
HTML
<button id="testBtn" type="button">Click Me!</button>
<div id="message"> <i class="fa fa-spinner fa-spin"></i>
<ul id='state'>
<li>Message Log... (this item only for testing)</li>
</ul>
</div>
CSS
ul {
margin: 5px;
border: 2px dashed #999;
padding: 10px;
}
ul>li {
line-height:30px;
list-style:none;
border-bottom:1px dashed silver;
}
JavaScript
//Assumption => delayTime [0: Start, >0: Complete, undefined: for_other_cases ]
function displayMessage(statusText, delayTime) {
var clear = function () {
$("#state", this).empty();
},
$m = $('#message').show();
if (delayTime == 0) clear.call($m);
$('<li/>', {
text: statusText
}).appendTo($m.children('#state'));
if (delayTime) $m.fadeOut(delayTime, clear);
}
function runAjax() {
$.ajax({
dataType: "jsonp",
url: 'http://jsfiddle.net/echo/jsonp/',
beforeSend: function () {
displayMessage("Request Started...", 0);
},
data: {
'text': 'some text',
'text2': 'another text'
}
}).done(function (response) {
displayMessage("Request Processed successfully!");
}).fail(function () {
displayMessage("Request failed!");
}).always(function () {
displayMessage("Action finished and status message will be cleared in 3 seconds", 3000);
});
}
$(function () {
$("#testBtn").on("click", runAjax);
});