I want to show loading spinner on Ajax call. I tried spin.js
library but it didn’t work. Here is my JavaScript function, which using Ajax call.
function sendRequest() {
$.ajax({
url: '/spinner',
type: 'get',
contentType: "application/json",
success: function (resp) {
$('#spinner').append(resp.data);
console.log(resp.data);
},
error: function (){
console.log("Oops!");
}
}
);
}
My HTML code:
<html>
<head>
<link type="text/css" rel="stylesheet" href="../resources/css/style.css"/>
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.5.0/pure-min.css">
<script type="text/javascript" charset="utf-8" src="../resources/js/jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="../resources/js/send.js"></script>
<script type="text/javascript" charset="utf-8" src="../resources/js/jquery.spin.js"></script>
<script type="text/javascript" charset="utf-8" src="../resources/js/spin.js"></script>
</head>
<body>
<button id="butt" class="pure-button pure-button-primary" onclick="sendRequest()">Press me!</button>
<div id="spinner">Greeting!</div>
</body>
</html>
-CSS-
#spinner {
text-align: center;
font-size: 100px;
color: #FFFFFF;
margin: 25px 350px 350px 350px;
background: #ad9ea4;
position: relative;
padding: 50px;
}
On server side I have a little delay (5 seconds). Actually I want to show spinner for this 5 secs. How can I add animation spinner into my page?
You don't need any libraries to do this. Just add an image to your markup, have it hidden by default, show it when you send a request and hide it when your request is done.
JavaScript
function sendRequest() {
// show spinner
$('#spinner').show();
$.ajax({
url: '/spinner',
type: 'get',
contentType: "application/json",
success: function (resp) {
$('#spinner').append(resp.data);
console.log(resp.data);
},
error: function () {
console.log("Oops!");
}
}).done(function () {
// hide spinner
$('#spinner').hide();
});
}
HTML
<img src="path/to/img.png" id="spinner"/>
CSS (you may want to edit this)
#spinner{
display: none;
position: absolute;
left: 50%;
top: 20%;
}