I'm having an AJAX request on the page.
Is there a way to find when a AJAX-call is triggered on the page.
In jQuery or javascript to find or initiate a function with AJAX request is called on a page.
See ajaxStart and ajax events. Example:
$("#loading").bind("ajaxSend", function(){
$(this).show();
}).bind("ajaxComplete", function(){
$(this).hide();
});
You can bind a function to a JQuery object to be completed when any AJAX call completes.
$('#status').ajaxComplete(function(event, request, settings) {
// Do stuff here...
});
See the documentation.
If you want to set a complete function for a single AJAX call, use the low-level $.ajax() function and setting a function for the complete attribute.
$.ajax({
// ...
complete: function(request, settings) {
// Do stuff here...
},
// ...
});
Note: the documentation seems to contradict itself in specifying the number of arguments to the complete() function. It may take some fiddling.
Related
I have two functions in jQuery that I want to fire in a specific order. The first function is an ajax function which updates a partial view. The other one is supposed to do some styling on the partial view, once the ajax function has completed - this function takes a parameter.
ajaxFunction();
stylingFunction(params);
I have tried the following:
ajaxFunction(function() {
stylingFunction(params)
});
Also, I have tried to use a callback:
ajaxFunction(stylingfunction(params));
ajaxFunction(callback)
{
//Do update
callback()
}
None of these do however work. The styling appears shortly where after it dissapears because the partial view is getting updated. Where am I going wrong here?
Both functions are written in my "parent" view.
You can use .done() and .fail() chained to the $.ajax call ...
I created a couple callback functions with psuedo-code inside the successCallback() since you said you only need to run the styling function "sometimes". You will want to test whatever condition inside that function to determine if you want to run the styling function. Hope this helps.
(function($) {
$(function() { //document.ready
$.ajax({ cache: false,
url: "/blah/vlah/lah",
data: { somedata: somedata }
})
.done(successCallback)
.fail(failCallback);
});
function successCallback(data) {
if (someCondition) {
stylingFunction(params);
}
};
function failCallback(jqXHR, status, error) {
console.log(jqXHR);
console.log(error);
console.log(status);
};
})(jQuery);
I created another gist which handles ajax event delegation, you may want to review and incorporate anything that seems helpful to your situation.
https://gist.github.com/inceptzero/a753d020648f49da90f8
I also created this gist on github for an ajax request queue which is a bit more elegant and robust.
https://gist.github.com/inceptzero/e64756f9162ca6aeeee5
Since you are using jQuery you could const ajaxFunc = callback => $.ajax({...}).done( data => callback) Also you could use async/await. You can read more about it on MDN.
I have a website which computes the performance of each server. One of the requirements is the center partial page which are about performances must be finish loading first before doing another function in the background.
This center partial page uses ajax calls. They are being defined at the document.ready of the js file:
$(document).ready(function () {
// ajax call here
// another ajax call here
// third ajax call here
});
Then the function that I wanted to execute after the function inside the document ready is done:
function functionA() {
// some codes here
});
I tried using this:
$.when(document).ready(function () {
}).done(functionA);
but I can't make it run .. Any suggestions would be gladly appreciated. Thanks in advance!
The first letter in AJAX stands for asynchronous which means that at the end of your document.ready event, they could be off somewhere else doing some processing. The document.ready will not wait for them to finish.
You need to set up jQuery using .when to tell you when all three AJAX calls are complete:
// Document.ready
$(function() {
// Any synchronous code you may do on DOM ready goes here
// Set up the promise
$.when(
// Pass in all your AJAX calls.
$.ajax({ url: "/AjaxCall1?param=true" }),
$.ajax({ url: "/AjaxCall2?param=1" }),
$.ajax({ url: "/AjaxCall3?param=yup" })
).then(function() {
console.log("All AJAX requests finished");
}, function() {
console.log("Something went wrong :(");
});
});
Here is a way to deal with DOM ready event and Ajax calls at the same time :
var init, ajax1, ajax2, domready;
ajax1 = $.ajax({ url: '/1' });
ajax2 = $.ajax({ url: '/2' });
domready = $.Deferred();
$(domready.resolve);
init = $.when(domready, ajax1, ajax2);
http://api.jquery.com/category/deferred-object/
Then you don't need to care about the code above any longer :
init.done(function () { alert('success'); });
init.fail(function () { alert('failure'); });
init.done(function ($, response1, response2) {
alert(response2[0]); // shows the data from the second Ajax call
});
Here is a live demo : http://jsfiddle.net/wared/s22dT/.
About your try, jQuery.when() returns a Promise object which has no ready method :
$.when().ready() // TypeError: Object #<Object> has no method 'ready'
http://api.jquery.com/jQuery.when/
What I want is to add a loader bar to my HTML, while my method does some time consuming AJAX calls and DOM manipulation.
The problem is, that show() method won't show the loader bar until the AJAX calls are done, how do I fix this?
I want to force the show() method, then do AJAX calls and DOM stuff, then force the hide() method.
Method doing AJAX calls:
$('.my-button').on('click', function(){
$('#display-loader').show();
// ajax and dom manipulation
$('#display-loader').hide();
});
EDIT: Seems like there's some misunderstanding as to what my problem is. If I change my code to this:
$('.my-button').on('click', function(){
$('#display-loader').show();
// ajax and dom manipulation
});
It still won't SHOW the loader bar, untill the AJAX methods are done, it's like it skips the show() method, does AJAX stuff, and then calls the show() afterwards.
All the AJAX calls have async set to false. I have 5 AJAX calls, and each AJAX call relies on the data fetched from the previous call, I have no way to set the async to true, is there a way to get around this, and force the DOM to display the image, and then do AJAX calls?
you can do next:
showLoader();
$.ajax({
type : 'POST',
url : url,
data : postData,
success : function (returnData) {
},
error : function (xhr, textStatus, errorThrown) {
},
complete : function (){
hideLoader();
}
});
You need to call hideLoader() within AJAX success function, to hide after ajax operation. As AJAX is asynchronous, so in your code hideLoader() execute before finish ajax call and done dom stuff.
$('.my-button').on('click', function(){
showLoader();
$.ajax({
....
success: function() {
hideLoader();
}
});
});
according to #Esailija comment to hide after complete callback do like:
$('.my-button').on('click', function(){
showLoader();
$.ajax({
....,
success: function(){
},
complete: function() {
hideLoader();
}
})
});
I recommend maybe the following way:
$.ajax({
.....
}).done(function () {
hideLoader();
});
This will insure the loader goes away. If your ajax isn't successful then the success callback will never be reached and then the loader will stay on the page.
But it depends on the scenario. You can also just put it in your error callback.
I am trying to override the jQuery ajax function to handle a default action on a success event but also executing the callback function that i am using in the options parameter.
What the purpose is there is tags returning in the response that I always want to strip out of the response for use elsewhere.
The scenario is:
Ajax submit
Ajax Success
--DEFAULT SUCCESS ACTION
--Call Ajax Success Callback
Can anyone help?
I have tried extending
jQuery.ajax
jQuery.ajaxSuccess
jQuery.ajax.done
The code I have is:
var _ajaxSuccess = jQuery.fn.ajaxSuccess;
$.fn.extend({
ajaxSuccess: function (a)
{
_ajaxSuccess.apply(this, a);
}
});
There is the global ajaxSuccess callback:
Whenever an Ajax request completes successfully, jQuery triggers the ajaxSuccess event. Any and all handlers that have been registered with the .ajaxSuccess() method are executed at this time.
That will let you call your own function on every successful AJAX call without interfering with the usual success callbacks.
There are various other global AJAX event handlers that you might want to look at too.
If those callbacks don't have the right timing or capabilities for you, then you could write your own wrapper for $.ajax and use that:
function wrapped_ajax(options) {
var success = options.success;
options.success = function(data, textStatus, jqXHR) {
// Do whatever needs to be done here.
if(success)
success(data, textStatus, jqXHR);
};
return $.ajax(options);
}
You can do whatever you need to the usual success callback parameters before calling the original success callback. You'd call wrapped_ajax in exactly the same way as $.ajax. You could use the same technique to hook into the other callbacks as well.
try jQuery.ajaxSetup it may help you ,read about it here
Do like this:
$.ajaxSuccess(function(){
//somethingtodo
});
Mentioned in http://tutorialzine.com/2011/06/15-powerful-jquery-tips-and-tricks-for-developers/ heading twelve.
$(document).ready(handler) executes once the DOM is fully loaded. If content is later added to the page using AJAX, which contains a $(document).ready(handler) function, this function is executed immediately, per the jQuery API. Additionally, .ready can only be called on a jQuery object matching the current document.
This is not what I want, however :)
How can I achieve this .ready type of functionality for data loaded via AJAX after .ready has already fired, in a cross-browser compliant manner?
EDIT:
Here's a very simplified example. I do have a problem I'm trying to solve, but I'm more interested in understanding the way to do this properly.
Basically, the .ready function in ajaxPage.html is firing before importantDependency.js is completely loaded, so the first load of ajaxPage, importantDependency is missing, but subsequent loads see it.
index.html
...
<script type="text/javascript">
$(document).ready(function() {
alert("The document is ready");
$('#myButton').click(function() {
$('<div></div>').dialog({
open: function () {
$(this).load('ajaxPage.html');
}
});
});
});
</script>
...
ajaxPage.html
...
<script type="text/javascript" src="importantDependency.js"></script>
<script type="text/javascript">
$(document).ready() {
$('#thing').leverageImportantDependency();
});
</script>
...
EDIT 2:
I want to do this FROM the loaded content, not from the page calling the content. Modifying the calling page means duplicating code in every instance where this is called. I'd like the behavior to be attached to the content, not the page calling it.
Generally, you will want to do something like this:
$("#container").load(function(html) {
// container has been filled up, and is
// ready for JS processing
doSomethingWithNewContent();
});
That is to say, fire off something once the content has been replaced, by utilizing the appropriate ajax callback. Other examples include:
$.get("foo.html", function(html) {
$("#container").html(html);
$("#container").find(".foo").fancyThing();
});
$.ajax({
url: 'foo.html',
type: 'post',
success: function(html) {
$("#container").html(html).find(".foo").hide();
}
});
See:
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jQuery.post/
http://api.jquery.com/jQuery.get/
http://api.jquery.com/jQuery.load/
EDIT: From what I understand from your edit, you want attach something, such as a an event handler or a plugin to some elements that keep getting replaced. There are a few ways to do this:
In the success callbacks, as
demonstrated above.
Using .live or
.delegate.
Using .liveQuery.
I'm not sure if I get your question, but when you have retrieved the data, you simply do whatever you want with it in the success handler of the ajax call:
$.ajax({
url: pageUrl,
success: function (data) {
$(".someContainer").html(data);
// TODO: This is your ready handler for the new content
}
});
You could use the complete property of an JQuery Ajax call. The complete function is called after success or error.
$.ajax({
url: "foo",
complete: function({
// I'm done
}
});
See: http://api.jquery.com/jQuery.ajax/