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...
Related
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
});
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');
});
};
I have an issue, do not know if it possible or not, how to check if my container is already loaded or not, because sometimes it is being loaded faster, sometimes slower and if it does not succeed in time getting an error in javaScript where gridview some functions are not recognizable(because the gridview is not loaded fast enough). Hope it is clear. Thanks for Your time.
Code:
function LoadPartial(partialUrl, container) {
$.ajax({
type: 'POST',
url: partialUrl,
success: function (returnData) {
$(container).html(returnData);
}
});
//.done(function () {
// return;
//});
}
you can use something like this.
$(".container").load(function (){
alert("Loaded :)");
});
Let me know in-case this doesn't work.
You can try using .data()
if ($('#mycontainer').data('loaded')) {
// your code
}
If you mean to find event when data received use "complete" function:
$.ajax({
type: 'POST',
url: partialUrl,
success: function (returnData) {
$(container).html(returnData);
},
complete: function() {
console.log('container filled with data');
}
});
I have a problem with an animation (fadeIn). It doesn't work after ajax. There is just NO ANIMATION but the content appears.
My code is like:
function ajax(varia) {
return $.ajax({
dataType: "html",
async: false,
type: 'POST',
url: 'index.php?fn=' + varia,
data: { token: "mytoken" }
});
}
Function with ajax works fine...
ajax("login").done(function (data) {
$("body").prepend(data);
}).done(function () {
// The #login have atribute style="display: none;"
$("#login").fadeIn(500);
});
This problem can be resolved with using delay before the fade, but i think it should be fine without this. Why it's not?
Thats probably because JavaScript is an asynchroneus language. What you are experiening is a synchronization issue:
Your ajax is done, you are firing DOM manipulation (prepend()), and imidiately after you fire it you do the fadeIn() but the fadeIn is complete before your data is prepended, so probably you'are calling fadeIn() on an element that doesn't exist yet.
Try this:
ajax("login").done(function (data) {
$("body").prepend(data);
setTimeout(function(){
$("#login").fadeIn(500);
},0);
});
And read this to understand why using timeout 0 is sometimes helpful: Why is setTimeout(fn, 0) sometimes useful?
By wrapping your action with setTimeout function you are basically telling: "wait until everything is done before doing this".
Here's the fiddle: jsFiddle
Did you try to put both calls into the same .done()-Block?
I think this should work:
ajax("login", "html").done(function (data) {
$("body").prepend(data);
// The #login have atribute style="display: none;"
$("#login").fadeIn(500);
});
In this case it should be guaranteed that the two lines of code are executed
successively.
I've made an live example here: http://jsfiddle.net/xLo93d29/
For me it works.
You should use "success" instead of "done":
function ajax(varia) {
$.ajax({
dataType: "html",
async: false,
type: 'POST',
url: 'index.php?fn=' + varia,
data: { token: "mytoken" },
success: function(data) {
$("body").prepend(data);
// The #login have atribute style="display: none;"
$("#login").fadeIn(500);
}
});
}
ajax("login", "html");
May be you can do like this
.done(function (data) {
var $data = $(data).hide();
$data.prependTo($("body"));
$data.fadeIn(500);
});
I am using jQuery getJSON() function. This function getting data with no problem. But sometimes waiting, waiting waiting... And my loading bar showing loading loading loadin at center of page.
So jQuery ajax() function have an timeout variable. But i want to use getJSON function. And i think that i can use ajaxStart() and ajaxStop() functions. But how?
$('.loadingDiv')
.hide()
.ajaxStart(function() {
$(this).fadeIn();
setTimeout("throw '';",15000) //i used this but didn't work
setTimeout("return;",15000) //i used this but didn't work
setTimeout("abort();",15000) //i used this but didn't work.(Abort all ajax events)
})
.ajaxStop(function() {
$(this).fadeOut();
});
getJSON() returns a promise on which you can call the abort function :
var p = $.getJSON(..., function(){ alert('success');});
setTimeout(function(){ p.abort(); }, 2000);
EDIT : but if your goal is just to abort if it takes too much time, then lethal-guitar's answer is better.
getJSON() is just a shorthand for the following:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
So you could use $.ajax() and specify the timeout option as desired. See also: http://api.jquery.com/jQuery.getJSON/
As lethal-guitar mentioned getJSON() function is just an shorthand for $.ajax(). If you want to detect if a timeout has occurred rather than an actual error use the code below.
var request = $.ajax({
dataType: "json",
url: url,
data: data,
success: function( ) { },
timeout: 2000
}).fail( function( xhr, status ) {
if( status == "timeout" ) {
// do stuff in case of timeout
}
});
There's always the nuclear route as well:
//Set AJAX timeout to 10 seconds
$.ajaxSetup({
timeout: 10*1000
});
This will set all the AJAX requests your program makes (even via $.getJSON) to have a time out of 10 seconds (or what have you).
the setTimeout function executes a set of code after a specified number of milisecons in the global scope.
The getJSON function (per the jQuery documentation here http://api.jquery.com/jQuery.getJSON/) is shorthand for:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
so you would want to make your call like so:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success,
timeout: 15000
});
$('.loadingDiv')
.hide()
.ajaxStart(function() {
$(this).fadeIn();
})
.ajaxStop(function() {
$(this).fadeOut();
});
I don't think any of these answers are ideal. I know this is years late, but what you want to do is use the success/error callback options of the .ajax(); method when receiving a JSONP response.
Example of how I would structure this:
// Call
$.ajax({
// URL you want to get
url: 'http://example.com/json?callback=?',
// Set a realistic time in milliseconds
timeout: 3000,
// Put in success callback function here, this example
// shows you the data you got back from the call
success: function(data) {
console.log(data);
},
// Put in an error handling function, just an alert in this case
error: function(badData) {
alert('The call was unsuccessful');
},
type: 'POST'
});