Toggle loader on $.post shorthand for Ajax call - javascript

I have this code for make a Ajax call:
$.post($form.attr('action'), $form.serialize(), 'json').done(function (data, textStatus, jqXHR) {
// Some logic here for done callback
// Redirect to another URL after 5 seconds
window.setTimeout(function () {
window.location = data.redirect_to;
}, 5000);
}).fail(function () {
// Some logic here for fail callback
})
That code works fine. Now I need to attach a "loader" to this Ajax call. I knew that I can attach this to $(document) as of jQuery 1.8+ docs expose (also found the same on this topic) so I have done the following:
$(function () {
// a bunch of logic here
}).ajaxStart(function () {
$('#loaderModal').modal('show');
$('#loaderModal').on('show.bs.modal', function (e) {
$('#loaderDiv').loader();
})
}).ajaxStop(function () {
$('#loaderModal').modal('hide');
$('#loaderModal').on('hidden.bs.modal', function (e) {
$('#loaderDiv').loader('destroy');
})
});
And once again that works but happens that I have other Ajax calls on the page (for validation purposes on some fields) and every time any of them run then the loader is show which is not correct since I need to attach only to the code shown above (the first piece of code). How I can accomplish this?
As a second part, an related to this post, some of the logic on done and fail callback trigger a Bootstrap Growl message and as you must have noticed I'm using the Twitter Bootstrap Modal component in which the loader is contained, so I'm fear that the call made to run the loader block in some way the second call when the callback for done is invoked, is that even possible? how fast is the execution of these events?
PS: If any of yours have a better solution to this then say and thanks in advance

Instead of using the global event handlers, show/hide the loader for the current ajax request like
//show the loader before the request
showLoader();
$.post($form.attr('action'), $form.serialize(), 'json').done(function (data, textStatus, jqXHR) {
// Some logic here for done callback
// Redirect to another URL after 5 seconds
window.setTimeout(function () {
window.location = data.redirect_to;
}, 5000);
}).fail(function () {
// Some logic here for fail callback
}).always(hideLoader) //hide the loader after the ajax request
function showLoader() {
$('#loaderModal').modal('show');
$('#loaderModal').on('show.bs.modal', function (e) {
$('#loaderDiv').loader();
})
}
function hideLoader() {
$('#loaderModal').modal('hide');
$('#loaderModal').on('hidden.bs.modal', function (e) {
$('#loaderDiv').loader('destroy');
})
}

Why not put your loading scripts into a function so you can call them at will? That way they fit into the logic of your code instead of running every time.
function startLoad() {
.ajaxStart(function () {
$('#loaderModal').modal('show');
$('#loaderModal').on('show.bs.modal', function (e) {
$('#loaderDiv').loader();
})
})
}
function stopLoad() {
.ajaxStop(function () {
$('#loaderModal').modal('hide');
$('#loaderModal').on('hidden.bs.modal', function (e) {
$('#loaderDiv').loader('destroy');
})
});
}

Related

Changing modal content breaks AJAX events

I use jquery-ujs for ajax requests (data-remote="true"). My problem is, that the first request is okay, and while the second is running, it breaks. Whenever I call in the events $('#modal').empty() or $('#modal').text('') or $('#modal').html(''), no more events are going to be called.
To be clear, here's the code:
$(document).on('ajax:beforeSend', function () {
console.log('beforeSend');
$('#modal').empty().modal('show');
});
$(document).on('ajax:send', function () {
console.log('send');
});
$(document).on('ajax:success', function (e, xhr) {
console.log('success');
$('#modal').html(xhr).drags({ handle: '.modal-header' }).modal('show');
if (typeof doWork === 'function') {
doWork();
}
});
$(document).on('ajax:complete', function () {
console.log('complete');
});
And the console output:
beforeSend
send
success
complete
beforeSend
If I move $('#modal').empty().modal('show'); to the send event, then it is going to be called, but the success method is never called anymore (neither error neither complete, nothing more).
This problem annoys me for more hours now... Thank you for your help.
How about to move empty() to the ajax:complete?
In this case, when your modal closes, it opens empty for the next use and is ready for reuse.
I suggest that you put this command in the last step so that it does not cause any problems. Like the following:
$(document).on('ajax:complete', function () { console.log('complete'); . . . . $('#modal').empty(); });
I believe that this is not the best solution and there are definitely other solutions. But I hope this solution will solve your problem.
$('#modal').on('hidden.bs.modal', function () {
$(this).empty()
})
My workaround was to avoid using jquery-ujs events and using global ajax events, so my final working code is:
$(document).ajaxSend(function () {
$('#modal').empty().modal('show');
});
$(document).ajaxSuccess(function (e, xhr) {
$('#modal').html(xhr.responseText).drags({ handle: '.modal-header' }).modal('show');
if (typeof doWork === 'function') {
doWork();
}
});

Is possible in on click function in jQuery wait for ajax complete and then do some code?

I want show modal after ajax is complete, here is my code:
$('.mymodalbtn').on('click', function (e) {
modalWindow = $(this).attr('data-target');
// alert(modalWindow);
$(document).ajaxStop(function () {
//0 === $.active
$(modalWindow).modal('show');
});
});
It is possible to do that? Now modal show after every ajax complete.
Thank you.
You can use .ajaxComplete() method of ajax request,which registers a handler to be called when Ajax request is completed.
Read more here.
Use complete event when your ajax call completed.
$('.mymodalbtn').on('click', function (e) {
modalWindow = $(this).attr('data-target');
$.ajax({
type: 'GET',
url: 'your_url',
success: function (responseData, textStatus) {
},
complete: function (textStatus) {
$(modalWindow).modal('show');
},
error: function (responseData)
{
}
});
});
I'm not sure about the way you're doing an ajax call, but I've been able to do it with the post super global
$_post(phpfile.php, $_post(phpfile.php, {variables to send}, function) you can use data as a parameter for the function and it will be anything that PHP echoes including error messages
Thank you for inspiration finally I do it this way.
global variable:
window.modal = "";
on click function:
$('.mymodalbtn').on('click', function (e) {
modalWindow = $(this).attr('data-target');
window.modal = modalWindow;
});
and ajax complete:
$(document).ajaxComplete(function (event, request, settings) {
if(window.modal != ""){
$(window.modal).modal('show');
window.modal = "";
}
});
Hope it is allright :-)
try to use setTimeout.
setTimeout(function(){
$('#mymodal').modal('show');
},4000);
Yes it is possible. You can use .ajaxStop() or .ajaxComplete() or in .ajaxSuccess()

$.when().then() not working with nested ajax calls

I have been trying to scroll the page to a dynamic div that is created by the an ajax call.
When #divnotifications div clicked (below), I make the first ajax call that adds the Post details, then within this ajax call, another ajax call is made to add the related comments to the div.
The part explained so far works great. Then, I use $.when().then() to scroll to a div item created based on the ajax calls. However, the page does not scroll to the element that was created by LoadCommentsForPost ajax call.
Did I get the logic of $.when().then() wrong?
$(document).on('click', '#divnotifications div', function (event) {
event.preventDefault();
$.ajax({
//other details
success: function (postid) {
$.when(DisplayPostWithFullDetails(postid)).then(function () {
//scroll to the content created by
//LoadCommentsForPost function nested
//inside DisplayPostWithFullDetails
});
}
});
});
function DisplayPostWithFullDetails(postId) {
$.ajax({
//other details
success: function (post) {
//The code to build the div to display the post -- working fine
LoadCommentsForPost(post.PostId);
}
});
}
function LoadCommentsForPost(postid) {
$.ajax({
//other details
success: function (response) {
var comments = JSON.parse(response);
DisplayComments(comments);//builds the div to display the comments - working fine
}
});
}
UPDATED CODE
After receiving some feedback, I ended up with the following code. However, it is still not working. It works only if I add some delay to make sure the div is loaded:
$(document).on('click', '#divnotifications div', function (event) {
event.preventDefault();
$.ajax({
//other ajax stuff
success: function (postid) {
DisplayPostWithFullDetails(postid).done(function () {
setTimeout(function () {
var scrollto = $("div[data-" + type.toLowerCase() + "displayform='" + relateditem + "']").offset().top;
$("html, body").animate({ scrollTop: scrollto }, 600);
}, 500);
});
}
});
});
function DisplayPostWithFullDetails(postId) {
jQuery.support.cors = true;
return $.ajax({
//other ajax stuff
success: function (post) {
post = JSON.parse(post);
//display the post details
LoadCommentsForPost(post.PostId);
}
});
}
function LoadCommentsForPost(postid) {
var promise = new $.Deferred();
jQuery.support.cors = true;
$.ajax({
//other ajax stuff
success: function (response) {
var comments = JSON.parse(response);
DisplayComments(comments);//this is not ajax
promise.resolve('loadedcomments');
}
});
return promise;
}
Did I get the logic of $.when().then() wrong?
Yes, you need to return a promise from the functions if you want to use the function with $.when:
function DisplayPostWithFullDetails(postId) {
return $.ajax({...
// ^^^^^^
That said, wrapping a single promise in $.when is useless.
$.when(DisplayPostWithFullDetails(postid)).then(function () {
should just be:
DisplayPostWithFullDetail(postid).then(function () {
Did I get the logic of $.when().then() wrong?
No, but you are NOT returning the promise so you can't use the promise functions like .then().
UPDATE:
I use $.when().then() to scroll to a div item created based on the ajax calls. However, the page does not scroll to the element that was created by LoadCommentsForPost ajax call.
For me this means that you need to wait that both ajax calls are resolved.
This fiddle show how it should work emulating the ajax call using setTimeout Fiddle.
Your code may look similar to:
function DisplayPostWithFullDetails(postId) {
var promise = new $.Deferred();
$.ajax({
//other details
success: function (post) {
//The code to build the div to display the post -- working fine
LoadCommentsForPost(post.PostId).then(function() {
promise.resolve();
});
}
});
return promise;
}
function LoadCommentsForPost(postid) {
return $.ajax({
//other details
success: function (response) {
var comments = JSON.parse(response);
DisplayComments(comments);//builds the div to display the comments - working fine
}
});
}
Now when you execute the function DisplayPostWithFullDetails it return a promise.
So you can use .then() method;
DisplayPostWithFullDetails(postid)).then(function () {});
or...
var promise = DisplayPostWithFullDetails(postid);
promise.then(function(data){});
Also the major advantage of use $.when() is that you can execute the .then() method when all the promises that you pass to it are resolved.
There are not need to use it when you are waiting for a single promise.

jQuery ajax asyncrhonous calling

I'm trying to make some actions after an ajax call done with jquery.
I have seen that if i use a function like this:
function DownloadData() {
$.ajax({
url: "/api/AlbumsRest",
accepts: "application/json",
cache: false,
success: function () {
/*binding stuff*/
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error' + textStatus);
}
});
}
The ajax request it's done in async mode. I don't want to change it because i don't want to freeze the page. But i would like to make some actions (animations, effects etc) after this ajax is completed.
So, my question is, how can i to know if i'm at the end of this request without using the success event
If i call DownloadData function like this:
function DownloadNextData() {
DownloadData();
SlideOutAnimation();
SlideInAnimation();
}
I need to make slides after async request has been made.
Some idea ?
Using jQuery Deferred Objects you should return the result of $.ajax() from DownloadData
function DownloadData() {
return $.ajax({...});
}
and then you can register a function outside of your AJAX handler that'll only get called once the AJAX call has completed:
function DownloadNextData() {
DownloadData().done(function() {
SlideOutAnimation();
SlideInAnimation();
});
}
behold - your animation processing is completely decoupled from your AJAX function :)
To simplify things, .done can also actually take a list of function references:
function DownloadNextData() {
DownloadData().done(SlideOutAnimation, SlideInAnimation);
}
Note that in this case you can't supply your own function arguments - they'll actually get passed the contents of the AJAX data.
function DownloadData() {
return $.ajax({
url: "/api/AlbumsRest",
accepts: "application/json"
});
}
function DownloadNextData() {
SlideOutAnimation();
SlideInAnimation();
}
DownloadData().done(DownloadNextData);
Try $.ajaxcomplete. here is the documentation for it http://api.jquery.com/ajaxComplete/

My ajax calls are not causing my .ajaxStop function to be called

I have the following code
$(document).ready(function () {
$("html")
.ajaxStart(function () {
$(this).addClass("wait");
})
.ajaxStop(function () {
$(this).removeClass("wait");
});
});
$.ajax({
url: url
})
.done(onDone)
.fail(onFail);
When the ajax is executed it goes to the ajaxStart and the class wait is added.
When the ajax is completed it goes to the onDone function but never goes to
the ajaxStop anonymouns function.
Can someone give me some advice on this.

Categories

Resources