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>
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
}
});
<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");
});
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
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');
});
$(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>
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);
}
});
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, "");
Here is the working fiddle for the code. https://jsfiddle.net/vibs2006/c7wukc41/3/
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");
});
});
I usually use this since it's simpler and more 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>
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
});
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>
Related
Well long story short, I am trying hide a div inside Ajax success function depending on whether its visible or not. But don't understand why it isn't working. I can set it to hide simply and which works but in the console when I check I find that it keeps on setting the div to display:none even if it is already hidden.
JS
$(document).ready(function() {
$('#loading').show();
setInterval(function () {
$.ajax({
type: "GET",
url: "generate_list.php",
success: function (result) {
//$('#loading').hide();
$('#loading:visible').hide();
if(result != '') {
$('#empty_storage').hide();
$('#file_list').html(result);
}
else {
$('#file_list').html('');
$('#empty_storage').show();
}
}
});
}, 1700);
});
Toggle visibility
$(document).ready(function() {
$('#loading').css('visibility': 'visible');
setInterval(function () {
$.ajax({
type: "GET",
url: "generate_list.php",
success: function (result) {
if ($('#loading').css('visibility') == 'visible') {
$('#loading').css('visibility','hidden');
}
if(result != '') {
$('#empty_storage').hide();
$('#file_list').html(result);
}
else {
$('#file_list').html('');
$('#empty_storage').show();
}
}
});
}, 1700);
});
CSS : Initially loader will be hidden
#loading {
visibility : hidden;
}
So go with visibility property if you want to check the visibility. But if you want to use .hide() or .show() then it depends on display property
Visibility : http://www.w3schools.com/cssref/pr_class_visibility.asp
Display : http://www.w3schools.com/cssref/pr_class_display.asp
Sample Demo : https://jsbin.com/jiluren/11/edit?html,css,js,output
Hope this helps. Thanks !
Your problem might be that you misplaced the call of showing the loading indicator. You call $('#loading').show(); only once, before starting the setInterval iteration. So the first time your #loading gets hidden, it will stay hidden forever. You should call $('#loading').show(); before each ajax call like this.
$(document).ready(function() {
setInterval(function () {
$('#loading').show();
$.ajax({
type: "GET",
url: "generate_list.php",
success: function (result) {
//$('#loading').hide();
$('#loading:visible').hide();
if(result != '') {
$('#empty_storage').hide();
$('#file_list').html(result);
}
else {
$('#file_list').html('');
$('#empty_storage').show();
}
}
});
}, 1700);
});
Also, note that for such a loading indication it's better to hide it in the always callback of the promise returned by $.ajax. That way the loading panel will be hidden also when an error occures, and the success callback is not called. I mean something like thi.
$("#loading").show();
$.ajax({ ... })
.always(function() {
$("#loading").hide();
});
If i understand your requirement , you need to show the loading icon before ajax call and hide it once ajax call completes
In that case there are predefined callback functions avialable
beforeSend: function (xhr) {
$("#loaderforsearch").show()
},
complete: function()
{
$("#loaderforsearch").hide();
},
I have loading div as following:
CSS:
.loader {
border: 8px solid #f3f3f3;
border-radius: 50%;
border-top: 8px solid gray;
width: 60px;
height: 60px;
-webkit-animation: spin 2s linear infinite;
animation: spin 2s linear infinite;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
#-webkit-keyframes spin {
0% {
-webkit-transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(360deg);
}
}
#keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
HTML:
<div class="loader"></div>
<div>
<button onclick="generateOrder();">Create Order</button>
</div>
Javascript:
function generateOrder() {
$('.loader').css('display', 'block');
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: oDataUri,
data: jsonPO,
async: false,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
for (var i = 0; i < data.results.length; i++) {
AddProducts(data.results[i].ProductID, data.results[i].ProductName)
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
reloadGridData(); //it will call ajax and reload all data.
$('.loader').css('display', 'none');
}
function AddProducts(productID, productName) {
//$('.loader').css('display', 'block');
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: oDataUri,
data: jsonPO,
async: false,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
for (var i = 0; i < data.results.length; i++) {
//more AJAX call with async: false
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
//$('.loader').css('display', 'none');
}
In Above case, loading is working fine in Mozila Firefox but when I am trying to use in Google Chrome, it doesn't work.
I can't set Async to True. Also I have multiple Ajax call.
Please suggest me solution of it.
Why note use the jQuery ajaxStart() and ajaxStop() methods to run your code.
ajaxStart Document
This is a global event handler which gets fired when ever an ajax call is occurred. The same principle goes to ajaxStop as well. You could search ajaxStop in google to get the documentation. Pretty easy to use.
Is just a dirty quick suggestion, not a pretty solution at all (and no tested):
Declare a global var to store the total ajax calls count (without async), and initiate the loader and the first ajax call
ajax_count = 1;
$ajax({
// ...
});
Increase the ajax call count on success:
ajax_count = data.results.length;
2.1. and decrease ajax_count and check if is the less or equal to 0:
ajax_count--;
if (ajax_count <= 0) {
$('.loader').css("display":"none");
}
Increase the ajax_count in the second ajax success callback calls level:
ajax_count += data.results.length;
3.1. and decrease ajax_count and check if is the less or equal to 0:
ajax_count--;
if (ajax_count <= 0) {
$('.loader').css("display":"none");
}
On the ajax third level success callback decrease and compare ajax_count too
Refactor the code as you want (encapsulate check, handle possible error - decrease and check on error callback too, or use the complete callback, ...)
the only 2 way i can think of are:
find which ajax calls finishes in the end. and in the success block of it call $('.loader').css("display":"none");.
register an even when the data that you must have before showing the page is available. and create an event listener to listen to it. when the data is available the event will be fired. the listener will listen and call $('.loader').css("display":"none"); and deregister the event.
that's all folks!
I´ve got a dropdown field where the user can change values via ajax. When the change-event occurs and the data is saved in the database, the user gets a visual "success-feedback" by making the row which contains the dropdownfield glow green.
This works fine so far, but the glow animation (css) fires only if the row loses focus / if i hover out of the row with the mouse (no need to click). I would appreciate any advices; maybe the whole concept of how i´m doing this glow is wrong (putting it in "success" in the ajax-call).
javascript:
$("[name='dropdown_status']").on('change', function() {
var tr = $(this).closest('tr');
var bestell_id = $(this).attr('id');
$.ajax({
type: 'POST',
url: '/files/ajax/wm_change_status_dt.php',
data: {
id_bestell: bestell_id,
id_status: $(this).val()
},
success: function(data) {
tr.addClass('dropdown_anim');
tr.one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {
tr.removeClass('dropdown_anim');
});
},
error: function(jqXHR, status, err) {
alert(status + ': ' + err);
}
});
}
css:
.dropdown_anim {
background: transparent;
animation: color-me-in 1s;
}
#keyframes color-me-in {
0% {
background: transparent;
}
/* Adding a step in the middle */
50% {
background: #D3FCC7;
}
100% {
background: transparent;
}
}
Please try following syntax (and add dropdown element id dropdown_status)
$(document).on("change", "#dropdown_status", function() {
var tr = $(this).closest('tr');
var bestell_id = $(this).attr('id');
$.ajax({
type: 'POST',
url: '/files/ajax/wm_change_status_dt.php',
data: {
id_bestell: bestell_id,
id_status: $(this).val()
},
success: function(data) {
tr.addClass('dropdown_anim');
tr.one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {
tr.removeClass('dropdown_anim');
});
},
error: function(jqXHR, status, err) {
alert(status + ': ' + err);
}
});
}
Okay, got it:
turned out, everything worked as it should. The only problem was css code, that was fired when the tablerow is hovered (changing it´s background-color). So, the green glow effect was not visible, or was only visible as soon as the row lost focus.
Hi everyone i have one problem with my ajax loading animation. The problem is when i hover any image the loading animation active under all images.
Like this FIDDLE
I want to make when i hover first image then .ajax-loading activated for only that image. and if i hover second image then .ajax-loading active for only second image ext..
Anyone can help me here ?
CSS
.ajax-loading {
transition: all 0.3s;
opacity: 0;
z-index: -1;
}
.ajax-loading.active {
opacity: 1;
z-index: 100;
}
and AJAX
$(document).ready(function () {
function showProfileTooltip(e, id) {
//send id & get info from get_profile.php
$.ajax({
url: '/echo/html/',
data: {
html: response,
delay: 0
},
method: 'post',
beforeSend: function() {
$('.ajax-loading').addClass('active');
},
success: function (returnHtml) {
e.find('.user-container').empty().html(returnHtml).promise().done(function () {
$('.the-container').addClass('loaded');
});
}
}).complete(function() {
$('.ajax-loading').removeClass('active');
});
}
function hideProfileTooltip() {
$('.the-container').removeClass('loaded');
}
$('.the-container').hover(function (e) {
var id = $(this).find('.summary').attr('data-id');
showProfileTooltip($(this), id);
}, function () {
hideProfileTooltip();
});
});
The problem is that the beforeSend function activate the class active for all the elements with the class .ajax-loading.
Since you're passing the jQuery object that is receiving the hover to the function, you can take advantage of that and add the class active only to those elements with the class .ajax-loading under it.
beforeSend: function() {
$('.ajax-loading',e).addClass('active');// Note the ,e that I added
},
Fiddle
Hope it helps.
i want to simply show the content after load not fadeIn how is it possible?
$(function() {
$('.hovers').click(function(event) {
var target = $(this).attr('href');
window.location.hash = target;
$.ajax({
url: target,
success: function(data) {
$('#allcontent')
.fadeOut('slow', function() {
$(this).html(data).fadeIn('slow');
});
}
});
return false;
});
});
maybe i use .show() ?
Thanks for help
success: function(data) {
$('#allcontent').html(data).show();
}
Just fadeIn 0 , which happens immediately
$(this).html(data).fadeIn(0);
also you might want to do this
$(this).html(data).delay(2000).fadeIn(0);
adding a delay of 2 seconds or however much you want, and then show immediately