I want to have a function called for every ajaxComplete call regardless of the ajax call. I know I can set a default value using my spinner by saying ('#spinner').ajaxComplete(complete) however if I have an ajax request that implements it's own complete my default complete method is not called.
How can I make a central function get called when any ajax call has completed??
Attach your ajaxComplete to the document; the ajax event will bubble up:
$(document).ajaxComplete(function(e, xhr, settings) {
// Do whatever you need here.
});
Attach the ajaxComplete listener to the DOM. This allows us to monitor it for any
$(document).ajaxComplete(function(e,request, options){
//attach our listener for ajaxComplete to the DOM.
//whenever an ajax call is completed, the DOM will send this function
customAjaxCompleteFunction();
});
var customAjaxCompleteFunction = function(){
alert("Custom Function for Each ajax call on complete!");
}
Related
Is it possible to bind listeners to when an AJAX request is started in Can.JS? I want to integrate a little loading indicator in my Can.JS project so that users can see when data is being loaded from my server. Using the jQuery $.ajaxStart and $.ajaxSend events didn't work, however the $.ajaxComplete event did fire correctly.
In your example you are binding to the event on document.ready which is after you start the Ajax request. The complete log only shows because the document is ready and binds the event before the Ajax request returns. If you do everything in the correct order on document.ready like this:
$(document).ready(function(e){
$(document).ajaxStart(function(){
console.log('start');
}).ajaxComplete(function(){
console.log("Complete");
});
var TestModel = can.Model({
findAll: "GET http://jsfiddle.net/echo/json/"
});
TestModel.findAll({}, function(result){
alert(result);
});
});
It works as expected (see updated fiddle).
I'm using the .each method with the .getJSON method to print out objects in a JSON file. This works fine, however I am unable to add a click function to an element that has been printed out. I am trying to bind a function to the div with 'click' ID.
var loadData = function () {
$.getJSON("profiles2.json", function (data) {
var html = [];
html.push("<div id='click'>Click here</div>");
$.each(data.profiles, function (firstIndex, firstLevel) {
html.push("<h2>" + firstLevel.profileGroup + "</h2>");
});
$("#data").html(html.join(''));
});
};
$(document).ready(function () {
loadData();
$("#click").click(function () {
console.log('clicked');
});
});
$.getJSON() (like other Ajax methods) is asynchronous, so it returns immediately before the results have come back. So your loadData() method also returns immediately and you then try to bind a handler to an element not yet added.
Move the .click(...) binding into the callback of $.getJSON(), after adding the element(s), and it will work.
Alternatively, use a delegated event handler:
$("#data").on("click", "#click", function() {
console.log('clicked');
});
...which actually binds the handler to the parent element that does exist at the time. When a click occurs it then tests whether it was on an element that matched the selector in the second parameter.
And as an aside, don't bind click handlers to divs unless you don't care about people who are physically unable to (or simply choose not to) use a mouse or other pointing device. Use anchor elements (styled as you see fit) so that they're "click"-accessible via the keyboard and the mouse.
$.getJSON is an asynchronous call and probably hasn't finished by the time you are trying to bind to the element that it injects into your DOM. Put your binding inside the $.getJSON call after you append the element to the page at the bottom.
What is the event to do actions while $.post method is in progress jQuery.
Explained more clearly: I use $.post method in my code in PHP. I need to display loading image until the $.post returns a value!
My code
$("#wit").click(function(){
var story = $("#story").val();
$.post('diary/ajax/ajax.php', {newdiary:story},function(data){
if(data=="SORRY")
{
alert("Sorry! Try Again in few seconds");
}
else
{
}
});
});
Just display the loading image in the line before you make your post() call. Then hide the loading image in the callback function. Note for this sort of operation you should also have a callback for a failed call so that you can hide the image in case the call fails for some reason.
I have several HTML elements (buttons) that fire the same JQuery AJAX request. When the AJAX request returns successfully, I need to make some updates to the HTML element that triggered the AJAX request. I understand how to do this if I were to hardcode the id of the element to update, such as an item with an id of myDiv as shown in the code below, but I am unsure of how to handle a dynamic id that corresponds to the element that triggered the event.
$('body').on(
'click',
'#yt25',
function(){
jQuery.ajax({
'type':'POST',
'data':$("#custom-hazard-form").serialize()+"&ajaxRequest=hazard-form",
'success':function(data) {
$('#myDiv').html('This is the new text'),
}
'url':'#',
'cache':false
});
return false;
});
I figure one option is to send the id of the HTML element that triggered the event as a key-value pair in the ajax request 'data' option and then have it passed back to the client as part of the AJAX response. I could then grab the id and know which HTML element to update. Is that the best way to handle this or am I missing something more obvious? Thanks.
$('body').on(
'click',
'#yt25',
function(){
var _this = this;
jQuery.ajax({
'type':'POST',
'data':$("#custom-hazard-form").serialize()+"&ajaxRequest=hazard-form",
'success':function(data) {
$(_this).html('This is the new text'),
}
'url':'#',
'cache':false
});
return false;
});
You don't need to sent it along with the ajax request.
This is one variation. You can also do this be assinging some classes to the element and get those elements by that class will do.
This is easy enough to work around, but it would be nice if it was wrapped up in the global ajax setup
When I run an ajax call, I'd like to know which element/event trigger the ajax call in the beforeSend option.
Is there a concise way of doing this?
The beforeSend callback takes two arguments: the XMLHTTPRequest instance and the settings used by the current AJAX call.
Therefore, if you pass the triggering element and event in the context option, they will be available to beforeSend even if you define it in the global setup:
$.ajaxSetup({
beforeSend: function(xhr, settings) {
var element = settings.context.element;
var event = settings.context.event;
// Do something with 'element' and 'event'...
}
});
$("selector").click(function(e) {
$.ajax("url", {
// your settings,
context: {
element: this,
event: e
}
});
});
Start Here
Global Ajax Event Handlers
These methods register handlers to be called when certain events, such as initialization or completion, take place for any AJAX request on the page. The global events are fired on each AJAX request if the global property in jQuery.ajaxSetup() is true, which it is by default. Note: Global events are never fired for cross-domain script or JSONP requests, regardless of the value of global.
.ajaxComplete() // initialize in for all ajax request and set event in jQuery.ajaxSetup()
.ajaxComplete() - Register a handler to be called when Ajax requests complete. This is an Ajax Event.