It may be a trivial question, but I am wondering if there is way to somehow know when the last ajax call gets completed. So lets say I have 3 asynchronous ajax calls
$.ajax({
type: "GET",
datatype: "json",
url: <my service url 1>
})
.done(function() {
// handler
});
$.ajax({
type: "GET",
datatype: "json",
url: <my service url 2>
})
.done(function() {
// handler
});
$.ajax({
type: "GET",
datatype: "json",
url: <my service url 3>
})
.done(function() {
// handler
});
I want to show a progress bar when the first call starts and hide it when the last one finish. The issue is that even though I call them in sequence, because calls are asynchronous, I don't know how to tell when all calls finish. I could nest them one inside another, but then as far as I understand it will take much longer as one will have to wait for another to finish. Is there a way to sync it somehow?
I used to have the same need. If you can use jQuery, have a look there : http://lostechies.com/joshuaflanagan/2011/10/20/coordinating-multiple-ajax-requests-with-jquery-when/
Otherwise, you can pass a simple callback function through your AJAX call that comes back in your progress indicator update at the end of each async treatment.
Already answered, but consider using global events instead -
AjaxStart - Triggered when any ajax call starts
AjaxStop - Triggered when all ajax calls are finished
Example -
$( document ).ajaxStart(function() {
$( "#progressBar" ).show();
});
$( document ).ajaxStop(function() {
$( "#progressBar" ).hide();
});
But you will need to make sure that the second call begins before the first call is complete or atleast it should be triggered immediately after the first one completes.
Related
I've got 3-4 ajax calls that will be made at some point.
For one of those calls I'd like to trigger a function on the ajaxSend event which is global. This specific ajax call is not necesserily the first or last one in the sequence. It seems that if I attach the ajaxSend event to the $(document), my function will fire every other time that an ajaxSend event occurs. Here's what my code looks like:
//ajax call one
$.ajax({
type: "POST",
url: myUrl,
data: myData
});
//ajax call two <- let's say I'd like to fire ajaxSpecificFunc() here
$.ajax({
type: "POST",
url: myUrl,
data: myData
});
//ajax call three
$.ajax({
type: "POST",
url: myUrl,
data: myData
});
function ajaxSpecificFunc(){
$(document).on("ajaxSend", function() {
//Some code that should only happen on ajaxSend but for only one ajax call
});
}
EDIT: I am aware of global:false property for ajax, but do not wish to use it, as this would mean I would have to modify every new ajax call in the future to have ajaxSpecificFunc() continue to fire for the one specific ajax call
You can add beforeSend in jQuery.ajax():
$.ajax({
type: "POST",
url: myUrl,
data: myData,
beforeSend: ajaxSpecificFunc
});
As noted by A.Wolff, this way if we call this function it will bind the ajaxsend for each call. Instead you can remove it and just do the specific ones like:
function ajaxSpecificFunc(jqXHR, settings){
// you can work with the jqXhr and settings
}
If you can't bind the handler directly to the ajax call, and want to use the global handlers only then you can check the setting object to see whether the ajax call is your targeted on and if so then call your stuff
$(document).ajaxSend(function(event, jqXHR, settings) {
console.log('send', settings);
if (settings.url == 'myurl') {
//then do your stuff
}
})
Note: But this might become an overkill, and you should try to do it specific to your ajax call
I've some simple ajax calls to populate drop down lists:
window.addEventListener('load', function () { GetDropDownData('http://mysite/controller/action/parameters1', '#ddl1') });
..
window.addEventListener('load', function () { GetDropDownData('http://mysite/controller/action/parameters4', '#ddl4') });
$.ajax({
url: url,
cache: true,
crossDomain : true,
dataType: 'jsonp',
type: "GET",
success: function (data) {
$(id).html(data);
},
error: function (reponse) {
$(id).html("error : " + reponse.responseText);
}
});
if I use them individually are fast, but used together are slow. This is evident in the images below.
The first time I use 1 call and it is fast, the second time I use 2 calls and the previous becomes slow now. The same with multiple calls.
Why this? And, can I solve it avoiding to merge the calls in a single call?
Session locking? One call comes in, locks the session, the second has to wait for the first to finish
Try switching session off and see if it improves
(I had the same problem once)
NB This answer only applies if the calls are asynchronous (as per the other comment)
http://johnculviner.com/asp-net-concurrent-ajax-requests-and-session-state-blocking/
Is there a way to pause the rest of a function when you are waiting for a value to be returned from an asynchronous call with jQuery?
To achieve this "paused" behavior, you want to put the behavior inside the promise object. https://api.jquery.com/jQuery.ajax/
$.ajax({
url: "test.html",
data: myData
}).success(function() {
//put your code here this will only fire after it returns successfully
}).error(function() {
//This will fire if there is an error
});
What you are talking about would be a synchronous call, which is not recommended as it will freeze the UI.
Instead, use the callback provided in the jQuery call to perform the rest of your code:
function DoSomeCall()
{
$.post( "ajax/test.html", function( data ) {
//Do your follow on code in here, in the callback.
});
//Don't do any code here that relies on the AJAX being finished first.
}
Here's a question which has proved very difficult to find an answer online for.
Let's say a user runs an ajax function onclick to fill the contents of a div.
But, what if the ajax output is php, and for that onclick, i want other divs on the page to change in a manner that is dependent on the contents of div1?
This means I need to wait for div1 to actually change so i can use the ajax output of the php calculations to adjust div2 accordingly.
After some testing i've found out that i cant add a call to a second ajax function at the end of the first because it seems to run before the div content from the first ajax call actually changes.
So how can i trigger an ajax call onchange of the contents of a div?
All ajax calls take a callback to run when the call completes, put your logic in there.
You could use Jquery
$('#div1').change(function(){
doAjax( $(this).html() );
});
Or in the callback of the ajax
$.ajax({
url: 'http://yoururl.com',
type: 'post',
data: { key: value },
success: function( data ){
doAjax( data );
}
});
If you are aware of jquery, this is what you should try:
$.ajax({
traditional: true,
type: "post",
url: '<your_url>',
beforeSend: function () {
//your logic to perform operation before ajax request
},
data: {
//data to send
},
success: function(response) {
//your logic to perform operation after ajax request
//here make another ajax request
}
});
I have a little question. say i have a js function
$(function() {
$(".button").click(function(){
var id=$(this).attr('id');
var dataString = 'id='+ id ;
$.ajax({
type: "POST",
url: "download_number.php",
data: dataString,
cache: false,
success: function(html)
{
$("#div_"+id).html(html);
} });
window.open('File_download.php?file_id='+id, '_blank' );
});
as you can see window.open call is after $.ajax call
Does it guaratee that $.ajax call will get executed every time before the page reloads and if no then
shouldn't we declare window.open in success function?
In my opinion when there is slow response from server the page will reload first and it may happen that $.ajax call will be interrupted by window.open function
but i get a downvote for the same reason here stackoverflow.com/questions/12908138/how-to-get-the-id-or-name-of-related-file/
And Thanks for making my belief stronger
In your example, the window.open function will always (!) be called before the success callback function given to the ajax call. Ajax traffic is always asynchronous, whereas the window.open function resides in the synchronous JS <script> tag.
Since JavaScript is single-threaded, all synchronous statements will always be executed before any asynchronous functionality like ajax setTimeout animate etc.
$.ajax({
type: "POST",
url: "download_number.php",
data: dataString,
cache: false,
success: function(html) { // asynchronous functionality
$("#div_"+id).html(html);
}
});
// within synchronous script statements
window.open('File_download.php', '_blank' );
Yes, Ajax is asynchronous so you will open that window right after you started the XHR process. To download the processed data, open the new window from the success callback. Yet I'm not sure what you mean by "before the page reloads" - there is no code which does that.
Also I don't know how your server behaves, the file_download.php seems to be independent from your ajax call. Shouldn't you pass the download_number you received via ajax in there?