How to put a loader in ajax requests? - javascript

One is a small code that allows me to view error messages when the form fields are empty or when everything is fine. What I would like to do is enter a loader or text to indicate that the submitted action is being processed. I really don't know where to start, can someone help me understand how to achieve this?
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax Handling Error
var $form = $(this);
jQuery.post(
$form.attr('action'),
$form.serialize(),
function(data) {
jQuery('.newdiv').html(data);
}, 'json',
);
//Ajax function
jQuery.ajax({
type: "post",
data: jQuery(".mts-edit-account").serialize(),
});
});
});

Firstly put the loader in your HTML file where you want to display it. i.e: below the submit button
<img
src="https://thumbs.gfycat.com/PessimisticGlamorousDunnart-size_restricted.gif"
class="loader"
alt="Loader"
height=25
width=25
>
Then add CSS for this loader:
.loader{
display:none;
}
Then put the below code in jQuery:
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "your_url",
data: $(".mts-edit-account").serialize(),
beforeSend: function() {
$(".loader").show();
},
success: function(msg) {
$(".loader").hide();
}
});
});
});

AJAX requests using jQuery allows you to handle request completion, failure or success using the returned value from ajax() function. In your case you need to start by showing the loader before starting the request, then hide on completion. To do that, you can use always() function. That will make sure it's always called in case of success or failure.
// Show loader
jQuery.ajax({
// ..
}).always(() => {
// Hide loader
});

Related

Showing a loading div during a jQuery ajax call

Im trying to show a loading div while waiting for an ajax call to complete. I have tried a couple of methods but cant seem to get anything to work consistently.
with my current code it works if i have a break point on the function that shows the div once the ajax is complete.
Fiddle
var https = 'https://www.googleapis.com/calendar/v3/calendars/';
function HideCheckShowLoading(checkId) {
$("#check_" + checkId).hide('slow', function() {
$("#loading_" + checkId).show('slow');
});
};
function HideLoadingShowCheck(checkId) {
$("#loading_" + checkId).finish().hide('slow', function() {
$("#check_" + checkId).finish().show('slow');
});
};
$(document).ready(function() {
$('#get').click(function() {
HideCheckShowLoading(1);
$.ajax({
url: https,
dataType: 'jsonp',
type: "GET",
success: function(response) {
//do something
},
error: function() {
//do something else
}
}).done(function() {
HideLoadingShowCheck(1)
});
});
$('#get2').click(function() {
HideLoadingShowCheck(1);
});
});
#check_1
{
background-color:red;
}
#loading_1
{
background-color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="check_1">Check</div>
<div hidden id="loading_1">LOADING</div>
<button id="get">Get</button>
<button id="get2">Get2</button>
What i would like to happen is,
on the click of a button we hide the check div
we show the loading div
make the ajax call
if successful do something(Reload the contents of the check div)
hide the loading div
show the check div
As said I have tried a few methods that i have found but i repeatedly get stuck with just the loading div shown
Thanks
I believe you may be slightly over-complicating things here. Something simple like this would suffice:
$('#get').click(function() {
HideCheckShowLoading();
$.ajax({
url: https,
dataType: 'jsonp',
type: "GET",
success: function (response) {
//do something
},
error: function() {
//do something else
},
complete: HideLoadingShowCheck
});
});
If you don't want the HideLoadingShowCheck routine to happen after success or error (standard behavior of complete), you can just move a function call HideLoadingShowCheck(); into your success and error blocks instead of using complete.
When you add () to a function name, it calls it immediately and returns the result. What you want to do is pass the function itself, not the result of the function - and you do that without the ().
There's no need for the $.when (assuming HideCheckShowLoading() doesn't make an ajax call, the jquery animations work differently), and $.ajax returns the promise itself, so you can update your code to:
$(document).ready(function() {
$('#get').click(function() {
HideCheckShowLoading();
$.ajax({
url: https,
dataType: 'jsonp',
type: "GET",
success: function (response) {
//do something
},
error: function() {
//do something else
}
})
//.done(HideLoadingShowCheck);
.done(function() { HideLoadingShowCheck(otherparams); })
});
});
I would change the showcheck function to add .finish() incase it's still animating from the showhide:
function HideLoadingShowCheck() {
$("#loading").finish().hide('slow',function () {
$("#check").finish().show('slow');
});
};

JS, jQuery not working when I refresh part of page with Ajax

I have some JS files included in my page that are simple for displaying blocks on click ant etc..
On another part of page, I have a button. When I click it an ajax call is made that returns some values that I display on the page. To display it, I'm reloading part of page like this:
$(document).ready(function () {
$(document).on('click', '.add', function (e) {
$this = $(this);
$.ajax({
type: 'POST',
url: 'add',
dataType: 'JSON',
data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}else{
$('.test').load(" .test");
$('.sidebar').load(" .sidebar");
$('.top').load(" .top");
}
}
});
});
This reloads part of page, displays values and etc..
However, after the ajax call is made, the JS stops working. When I click my buttons, nothing happens. No errors or anything.
I think it has to do with the ajax when I refresh part of twig and it messes up the previously loaded JS files. But what can I do in that situation? Somehow refresh the loaded JS files? How?
You have to attach event listener on button starting from the container which doesn't get reloaded by Ajax request, like this:
//#mainCont is a container that doesn't get reloaded by Ajax
$("#mainCont").on("click", ".yourBtn", function(){
//do something
});
As said #Nacho M, you need to reinit listener from the loaded element, so you hsould have something like this :
function init() {
$(document).on('click', '.yourclass', function (e) {
//your content
}
// add every button who needs to be reloaded.
}
Init them on loading page first :
$("document").ready(function() {
init();
})
And on success of Ajax call :
$.ajax({
type: 'POST',
url: 'add',
dataType: 'JSON',
data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}else{
$('.test').load(" .test");
$('.sidebar').load(" .sidebar");
$('.top').load(" .top");
init();
}
}
});

Generic way to handle all AJAX calls

Is there a way to detect all AJAX calls (both GET and POST)? I need to do a generic way to show a loading div while the AJAX call process are running. Something like the code below:
$.ajax({
url: 'my/url',
type: "GET",
dataType: "json",
beforeSend: function() {
$('#loading').show();
},
success: function() {
$('#loading').hide();
// do some stuff...
}
Instead to call in every AJAX beforeSend() and success() behaviors (show and hide the loading div), I'm searching a generic way to handle it. When I have an AJAX call, I just do it:
$.ajax({
url: 'my/url',
type: "GET",
dataType: "json",
success: function() {
// do some stuff...
}
When that beforeSend() behavior is implicity in this request and the same for the success() hide behavior. Do you have any idea how can I treat this thing?
Thank you all!
Yes, you can do this using .ajaxStart() & .ajaxStop() methods like:
$(document).ready(function () {
$(document).ajaxStart(function () {
$('#loading').show();
}).ajaxStop(function () {
$('#loading').hide();
});
});
Funnily enough, I was trying to do this myself this morning!
$('#loading').bind('ajaxSend', function() {
$(this).show();
}).bind('ajaxStop', function() {
$(this).hide();
}).bind('ajaxError', function() {
$this.hide();
});
Obviously, lots of different ways to achieve this, but I prefer to bind the visibility of the loading message to the AJAX events, rather than the other way around...

make sure ajax request doesn't get fired multiple time

I was working on a simple form page and I was wondering what happens if someone clicks the submit button many many times (incase my shared hosting somehow seems to be slow at that time).
Also, incase anyone wants to look at my code
$.ajax({
url: "submit.php",
type: 'POST',
data: form,
success: function (msg) {
$(".ressult").html("Thank You!");
},
error: function () {
$(".result").html("Error");
}
});
Is there a way to make it so after the user clicks it once, it won't run it again until the first click is done?
Thank you
You can use jQuery's .one() function:
(function handleSubmit() {
$('#submitBtn').one('click', function() {
var $result = $('.result');
$.ajax({
url: 'submit.php',
type: 'POST',
data: form,
success: function (msg) {
$result.html('Thank You!');
handleSubmit(); // re-bind once.
},
error: function () {
$result.html('Error');
}
}); // End ajax()
}); // End one(click)
}()); // End self-invoked handleSubmit()
*Edit: * Added recursion for multiple submissions.
Use a boolean flag
if (window.isRunning) return;
window.isRunning = true;
$.ajax({
url:"submit.php",
type: 'POST',
data: form,
success: function (msg){
$(".ressult").html("Thank You!");
},
error: function (){
$(".result").html("Error");
},
complete : function () {
window.isRunning = false;
}
});
var $button = $(this);
$button.prop('disabled', true); // disable the button
$.ajax({
url:"submit.php",
type: 'POST',
data: form,
success: function (msg){
$(".ressult").html("Thank You!");
},
error: function (){
$(".result").html("Error");
},
complete: function() {
$button.prop('disabled', false); // enable it again
}
});
Have you considered replacing your submit button with a loader image while the query executes, then re-adding it once the query is complete?
EDIT: Using the loader image is a sort of universal "I'm doing something" indicator, but disabling the button would work too!
You could disable the submit button, before the ajax call is made. And then, if required, enable it on success.

What's a good way to display a loading image until an ajax query completes?

Right now it contacts the server every time a user toggles "Comments (X)"
I'd like to make it so as soon as a user clicks ".info .reply" (Comments (X)), an ajax loader appears just until the data is finished loading, then the loader disappears.
// Replies - Toggle display of comments
$('.info .reply').click( function() {
$('.reply', this.parentNode.parentNode).toggle();
return false;
});
// Load comments
$('.info .reply', this).mousedown( function() {
var id = $('form #id', this.parentNode.parentNode).val();
$.ajax({ url: location.href, type: 'post', data: 'id=' + id, dataType: 'json',
success: function(data) {
for (var i in data) {
// Do AJAX Updates
}
}
});
return false;
});
What's the proper way to do this?
Thanks!
Basically
Show the image on mousedown using show() or fadeIn() or whatever tickles your fancy, then hide it inside your success callback. Like this
$('.info .reply', this).mousedown( function() {
$("#loading-image").show(); // Show the progress indicator
var id = $('form #id', this.parentNode.parentNode).val();
$.ajax({ url: location.href, type: 'post', data: 'id=' + id, dataType: 'json',
success: function(data) {
$("#loading-image").hide(); // Hide the progress indicator
for (var i in data) {
// Do AJAX Updates
}
}
});
return false;
});
You can use a plugin such as jQuery BlockUI to do this. Just call $.blockUI() before calling $.ajax. Then at the end of the success event, call $.unblockUI().

Categories

Resources