Show a div during function call jquery - javascript

I'd like to display the #LoadingDiv while checkCoupon is firing, and have it disappear when it finishes, to show the function is in progress. checkCoupon is triggered by a button click (not displayed).
I've tried a variety of things including creating another function to include in onclick event, I've put this in different parts of the ajax call, and tried altering the CSS in different ways. It's still not working.
Any idea how to get this functionality and have this display properly at the beginning of the call starts?
function checkCoupon() {
var coupon = document.getElementById('couponCode').value;
var coupon_v = false;
$('#LoadingDiv').css('display', 'block');
$.ajax({
type: 'post',
url: 'coupon.php',
async: false,
data: {
'coupon': coupon
},
success: function(data) {
if (data != "empty") {
coupon_v = data;
}
}
})
}
<div id="LoadingDiv" style="display:none;">One Moment Please...<br />
<img src="images/progressbar.gif" class="displayed" alt="" />
</div>

You can hide the div on ajax complete function which is called when the request finishes (after the success or error callbacks are executed):
complete: function(){
$('#LoadingDiv').hide();
}

You can make use of jQuery's beforeSend and complete methods to address states before and after the call:
function checkCoupon() {
var coupon = document.querySelector('#couponCode').value;
var coupon_v = false;
let $loading = $('#LoadingDiv');
$.ajax({
type: 'post',
url: '.', //coupon.php
async: false,
data: {
'coupon': coupon
},
beforeSend: function() {
$loading.removeClass('hide')
},
success: function(data) {
if (data != "empty") {
coupon_v = data;
}
},
complete: function() {
// timeout only used for demo effect
window.setTimeout(function() {
$loading.addClass('hide')
}, 1500)
}
})
}
.hide {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="LoadingDiv" class="hide">One Moment Please...<br />
<img src="images/progressbar.gif" class="displayed" alt="" />
</div>
<input type="hidden" id="couponCode" value="3" />
<button onclick="checkCoupon()">Click</button>

I had the same issue. I know this is an older question by now, but obviously still relevant as I ran into the same conundrum.
I would call the showLoadingOverlay() method which would make the loading div visible, then run the function I wanted to run and then hide the loading overlay, but the overlay would never show. I finally found that the issue was that the function I was performing after showing the loading overlay was happening too quickly and it would pause the process of showing the overlay until it was done and then the hide function on the overlay was being called too quickly afterwards when the show method was able to resume. This is why it appeared that nothing was happening at all.
So, you need to delay the function you are trying to call (I used the setTimeout() method). The 400 in the setTimeout() method is 400 miliseconds that will be delayed before performing the processFunction method. Here is a generic way to accomplish your goal:
Javascript:
/******************************************************************************************
* Toggle loading overlay.
* ***************************************************************************************/
/**
* Toggle the loading overlay in order to prevent the user from performing any actions.
* The processFunction must call the endLoadOverlay method once it is finished.
* #param {any} processFunction The process to perform while the loading screen is active.
* This method must call the endLoadOverlay method once it is done.
*/
function startLoadOverlay(processFunction) {
$('#overlay').css('display', '');
setTimeout(processFunction, 400);
}
/**
* Ends the loading overlay.
* */
function endLoadOverlay() {
$('#overlay').css('display', 'none');
}
/******************************************************************************************
* End of toggle loading overlay.
* ***************************************************************************************/
Then when you call the startLoadOverlay() method pass the method that you want to accomplish through it. In my example I'm having a button click event call the overlay method:
HTML:
<button id="btnDoAction" type="button" onclick="startLoadOverlay(myFunctionToAccomplish);">Accomplish Something</button>
Remember, myFunctionToAccomplish() is the method that I want performed while the overlay is visible. NOTE: The method that you pass to the startLoadOverlay() method must call the endLoadOverlay() method after it is done processing in order to hide the loading overlay. So:
Javascript
function myFunctionToAccomplish() {
// Perform functionality.
//TODO: Add whatever functionality here.
// Once I'm done I need to call the endLoadOverlay() method in order to hide the loading overlay.
endLoadOverlay();
}
In case you are curious about my $('#overlay') element. The idea is basically from here: https://www.w3schools.com/howto/howto_css_overlay.asp

Related

Limit ajaxStart function to only 1 of 2 ajax functions

I have a loading.gif that launches each time the user makes an AJAX powered search. However, I've got some search fields that automatically show suggestions while the user types, also powered by AJAX.
Now my loading.gif appears on the user search as well as the search suggestions while typing. How do I limit my function that shows the loading.gif to only show when it's a user AJAX search and not a search-suggestion-while-typing AJAX search?
This is my function:
$(document).ajaxStart(function () {
$(".se-pre-con").fadeIn("fast");
}).ajaxStop(function () {
$(".se-pre-con").fadeOut("fast");
});
how about bind it with condition like if user is still on the search input then dont show the loading.gif else if the user is out of the search input or first contact on the search input then show the loading.gif (refer below)
first the global variable
var input_focus = false;
and then when the specified input is on focus
$("#specified_input").focus(function(){
//set the variable named 'input_focus' to true to reject the showing of the loader (loading.gif) or hide it.
input_focus = true;
}).blur(function(){
//when the specified input lose it focus then set the variable 'input_focus' to false so that the loader (loading.gif) is allowed to show
input_focus = false;
});
$.ajax({
url : 'my-url',
type : 'post',
data : {},
beforeSend : function(){
//check if input is on focus
if(input_focus !== true){
//show the loading.gif, assume that #loader
$("#loader").show();
}else{
//hide the loading.gif, assume that #loader
$("#loader").hide();
}
},
complete : function(){
//when the ajax request is complete
},
success : function(response){
//the response function
}
});
I'd tackle it by either of the following:
1) Add a global variable such as showLoadingAnimation and set it to true or false depending on the need. Within your ajaxStart and ajaxStop do the following:
$(document).ajaxStart(function () {
if (showLoadingAnimation) $(".se-pre-con").fadeIn("fast");
}).ajaxStop(function () {
if (showLoadingAnimation) $(".se-pre-con").fadeOut("fast");
});
2) Instead of changing the jQuery global settings, Wrap the jQuery method with your own method:
//only listen to ajaxStop event so that we can hide the animation
$(document).ajaxStop(function () {
$(".se-pre-con").fadeOut("fast");
});
function myAjax(params, showAnimation) {
if (showAnimation) $(".se-pre-con").fadeIn("fast");
$.ajax(params);
}
//in your code you instead of calling $.ajax({...}) simply use `myAjax({...})`
Hope this helps.

Waiting for all AJAX call than show dialog box

I am working on a dynamic online form website. In the main form, I have multiple sub-forms which can be added and deleted dynamically.
<div class='subform'>
//form fields
<input ...>
...
<button class='subform_submit'>
</div>
For each subform, I bind an AJAX call on the subform's submit button like this:
$('#main').on('click', '.subform_submit', function(){
// Get this subform's user input
...
$.ajax({
url: ..,
type: ..,
data: /* this subform's data */
});
});
So in that page, I may have 0 to 10 subforms depending on the user's selection.
I also have a main submit button on the bottom of the page, which can submit those subforms and the main form's data together.
$('#main').on('click', '#submit', function(e){
$('.subform_submit').click(); // Submit each subform
bootbox.confirm({ });
})
Once main submit button is clicked, I want to show a loading picture and then show a dialog box (I use bootbox.confirm() here) until all AJAX calls have completed.
This dialog box is telling user that whole form including sub-forms has been submitted.
But the problem is that each AJAX call may take 2 seconds to complete and I don't know how may calls may be pending completion. How can I write this main submit button so that it will:
Show the loading image immediately, and
Hide the loading image and show the dialog box after all AJAX calls have completed?
Keep track of how many sub-forms there are;
$subFormsCount = $('.subform').length;
Keep track of how many forms have been submitted;
$submittedForms = 0;
Each time a form finishes submitting, add to the $submittedForms;
$.ajax({
..
..
done: function(){
$submittedForms++;
}
})
Create a global timer to see if the number of submitted forms matches the total number of subforms. If true, hide the dialog box;
setInterval(function(){
if($submittedForms == $subFormsCount){
$('.dialog').show();
}
}, 50ms)
Edit
You could skip the global timer (as this will probably be a few milliseconds out) - include the check in your ajax.done instead;
$.ajax({
..
..
done: function(){
$submittedForms++;
if($submittedForms == $subFormsCount){
$('.dialog').show();
}
}
})
You want to use .done() in order to specify code that should wait until the AJAX asynchronous function completes.
$.ajax({
url:..,
type: ..,
data: /* this subform's data*/ })
.done(function() {
//Put code here
});
Have you tried .ajaxStop() event handler ?
$(document).ajaxStop(function() {
// place code to be executed on completion of last outstanding ajax call here
});
also, check this answer
I assume you have 9 subform and 1 main form.
Code for 8 subform will be same.
I use here async:false : Means next ajax will not be call until 1st one is not completed.
Sample Code Format :
var id = 5;
$.ajax({
url: ,
type: 'POST',
data: {'id':id},
dataType: 'JSON',
async: false,
error : function(xhr, textStatus, errorThrown) {
alert('An error occurred!');
},
success : function(response){
}
});
Just set variable in your last sub form that is 9th subform.
success : function(response){
var counter = true;
}
if(counter){
/* Code to show dialog.*/
}
You can use $.when to wait for each request to complete. Something like this should get you close. You'd basically want to store all the ajax requests in an array and pass that to when as the arguments.
$('#main').on('click', '.subform_submit', function () {
var formRequests = $('.subform').map(function () {
var $form = $(this);
return $.ajax({
url: '',
data: $form.serialzeArray()
});
}).get();
$.when.apply(undefined, formRequests).done(function () {
console.log('All done!');
});
});
Here goes a very similar little demo I just made up: https://jsfiddle.net/g9a06y4t/

jquery setTimeout few questions about it

i have a website with tags system like kind of the system that work on stackoverflow.
my questions about it is:
$("#area1 ul li").hover(function(){
var width= $(this).offset();
$(".flyout").css({"top":width.top+19,"left":width.left});
$(".flyout").toggle();
setTimeout(function() {
$.ajax({
url: web + "sources/queans/sql.php", type: "POST",
data: {
action: "taginfo",
tag: $(this).text(),
token: t,
ajax: "1"
},
success: function (output) {
$(".flyout").html(output);
}
});
}, 2000);
$(".flyout").html('<center><img style="margin-top:20px;" src="http://www.cloudynights.com/public/style_images/master/ajax_loading.gif" /> </center>');
});
Do this Jquery script is wait 2 seconds while the mouse are hover
the element?
if user remove the mouse hover the element do the query will still
running and execute the code? if no how can i stop the code before
it require from sql.php file data?
Do this Jquery script is wait 2 seconds while the mouse are hover the element?
Not exactly, once a user has hovered over the element, a timer is started and 2 seconds later the action is performed. The user does not have to remain hovering the element for this to happen.
if user remove the mouse hover the element do the query will still running and execute the code?
As specified above, the action will execute 2 seconds after first hovering the element, regardless of what the user does thereafter.
if no how can i stop the code before it require from sql.php file data?
Capture the result of the call to setTimeout into a variable (commonly called timerId or similar), and call clearTimeout(timerId) when the user stops hovering the element.
See the following simplified demo.
var timerId;
$('.container').hover(function(){
$('.message').text('Hover has been started, background will change in 5 seconds. Mouse out to cancel');
var $this = $(this);
timerId = setTimeout(function(){
$this.css('background-color','red');
},5000);
},
function(){
clearTimeout(timerId);
$('.message').text('Action cancelled');
});
.container{
width:300px;
height:300px;
border: 1px solid black
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div>Hover over me</div>
<div class="message"></div>
</div>
.hover() usually takes two arguments, handlerIn and handlerOut functions. As you have only one function, it will be invoked when the mouse pointer enters the element. My understanding is that you're displaying some pop-up next to element with some loading icon on hover, that's good because giving some visual feedback to the user encourages him to stay on that element.
setTimeout(callback,2000) will invoke that callback after waiting for minimum 2sec (it can be more - no guarantee on that ;)) but if the user leaves the element you're still firing the Ajax call without tracking that mouseleave event. So pass another function to hover() which will be invoked when the user leaves the element.
/* two variables outside hover scope to
hold reference to setTimeout & Ajax call*/
var timer, ajaxRequest;
$("#area1 ul li").hover(function(){
var width= $(this).offset();
$(".flyout").css({"top":width.top+19,"left":width.left});
$(".flyout").toggle();
timer = setTimeout(function() {
ajaxRequest = $.ajax({
url: web + "sources/queans/sql.php", type: "POST",
data: {
action: "taginfo",
tag: $(this).text(),
token: t,
ajax: "1"
},
success: function (output) {
$(".flyout").html(output);
}
});
}, 2000);
$(".flyout").html('<center><img style="margin-top:20px;" src="http://www.cloudynights.com/public/style_images/master/ajax_loading.gif" /> </center>');
},
function(){
// second callback to handle mouseleave
if(typeof ajaxRequest !== 'undefined'){
// abort the ongoing Ajax call
ajaxRequest.abort();
}else if(typeof timer !== 'undefined'){
// timeout callback is not invoked yet, so clear it
clearTimeout(timer);
}
// show some message in flyout or close the popup directly
});

How To Call Function on page Loading

I'm Using Web service using AJAX Call In My HTML Page . Web Service Returning Data Nearly 30 to 40 second's .
During This Loading Time I Need to Use Some Loading Gif Images After Data Completely Received Form Web Service The Loading Image Must Be Hide.
I'm Using Only HTML,JAVASCRIPT,CSS,J Query.
Any Idea Or Samples Needed.
I'm Using Following Code
$(document).ready(function () {
document.write('<img src="http://www.esta.org.uk/spinner.gif">');
});
$( window ).load(function() {
//This following Function Related To My Design
jQuery(".chosen").data("placeholder", "Select Frameworks...").chosen();
var config = {
'.chosen-select': {},
'.chosen-select-deselect': { allow_single_deselect: true },
'.chosen-select-no-single': { disable_search_threshold: 10 },
'.chosen-select-no-results': { no_results_text: 'Oops, nothing found!' },
'.chosen-select-width': { width: "95%" }
}
for (var selector in config) {
$(selector).chosen(config[selector]);
}
});
In The Above Code My Problem Is On Page Load Gif Image Show But It's Not Hide Only Gif Image Only Showing.
Put a hidden image on your page and as soon as your ajax call is made, make that image visible
$('#image').show();
$.ajax({
complete: function(){
$('#image').hide();
}
});
and hide that image again on Complete of Ajax call.
Use your ajax request callback (on success/failure) instead of page load.
When sending the request just show a gif animation by setting the Display to block
then when you have the data set the display to none
or use jquery
function showHourGlass()
{
$("#gifimage").show();
}
function hideHourGlass()
{
$("#gifimage").hide();
}
You ask for ideas, I have one sample -
http://www.myntra.com/shoes
load scroll down fastly this is the ajax jquery request which is exact output which you have mentioned in your question
Check source code
Jquery Ajax loading image while getting the data
This what the html looks like:
<button id="save">Load User</button>
<div id="loading"></div>
and the javascript:
$('#save').click(function () {
// add loading image to div
$('#loading').html('<img src="http://preloaders.net/preloaders/287/Filling%20broken%20ring.gif"> loading...');
// run ajax request
$.ajax({
type: "GET",
dataType: "json",
url: "https://api.github.com/users/jveldboom",
success: function (d) {
// replace div's content with returned data
// $('#loading').html('<img src="'+d.avatar_url+'"><br>'+d.login);
// setTimeout added to show loading
setTimeout(function () {
$('#loading').html('<img src="' + d.avatar_url + '"><br>' + d.login);
}, 2000);
}
});
});
I hope this will help you.

Loading indicator for xeditable

I am using X-Editable (earlier Bootstrap-Editable) for in-place editing.
While saving data on server takes approximately 2-3 seconds.
Meanwhile this time span, i want to put a loading indicator.
How do i implement this?
call an ajaxfunction to update contains the loading icon, like the function below:
function ajaxUpdate()
{
var def = '<img src="./images/loader.gif" />';
$('#loading').html(def);
$('#loading').show();
jQuery.post("<?php echo site_url('myController/updateDetails');?>", {
v1 : $('#v1').text(),
v2 : $('#v1').text(),
v3 : $('#v1').text()
},
function(response)
{
if(response==1)
{
//success area
$('#loading').hide();
}
else
{
// failure area
}
});
}
<div id="loading"></div>
when calling this function the loading image is displayed on the div with id loading
and after success of the ajax call it will be hidden.

Categories

Resources