this is my first time using ajax. and i don't have an idea where the ajaxStop takes place. I am using the ajaxStart to show a loading image and need the ajaxStop to hide the loading image. Please help.
I have this code to call a popup from "PageOne"
function ShowFixSteps(path, title){
var winHeight = parseInt(jQuery(window).height() - 100);
var winWidth = parseInt(jQuery(window).width() - 600);
jQuery.ajax({
url: path,
success: function(data) {
jQuery("#divPopup").load(path).dialog({
modal: true,
width: winWidth,
height: winHeight,
title: title,
position: "center"
});
}
});
jQuery("#divPopup").bind("dialogbeforeclose", function(){
jQuery("#divPopup").empty('');
});
}
And on my Master page, I have this code to check the start and stop of ajax call:
$(document).ajaxStart(function() {
alert('start');
});
$(document).ajaxStop(function() {
alert('stop');
});
$(document).ajaxError(function() {
alert('error');
});
It alerts the START but not the STOP: no ERROR also.
NOTE: START and STOP alerts are working on Chrome but not IE.
ajaxStop is triggered after all current AJAX requests have completed.
You can read more about ajaxStop using the jQuery API documentation.
You can use .ajaxStop() in the following manner:
$(document).ajaxStop(function() {
$('#loading-spinner').hide();
});
Or you could add :complete callback to your AJAX function, like so:
jQuery.ajax({
url: path,
success: function(data) {
jQuery("#divPopup").load(path).dialog({
modal: true,
width: winWidth,
height: winHeight,
title: title,
position: "center"
});
},
complete: function() {
// do something here when ajax stops
// like hiding the spinner or calling another function
}
});
And as you mentioned how to stop an AJAX request in one of your comments, here's how:
var ajax1 = $.ajax({
type: "POST",
url: "some.php",
...
});
ajax1.abort()
You could check if a specific AJAX request is running before aborting by doing this:
if (ajax1) {
ajax1.abort();
}
Or you could check to see if any ajax requests are running before aborting by doing something like this:
var ajax_inprocess = false;
$(document).ajaxStart(function() {
ajax_inprocess = true;
});
$(document).ajaxStop(function() {
ajax_inprocess = false;
});
if (ajax_inprocess == true) {
request.abort();
}
Beware using .abort() though, as it only stops the client-side code from listening for a response, it wont actually stop the server from working. There are actually a few major caveats using this, so make sure you read about it first.
UPDATED ANSWER FOR UPDATED QUESTION
For IE problem, try using:
$(document).ajaxComplete(function() {
// do something
})
Instead of ajaxStop(). ajaxComplete() will fire each time an AJAX request finishes, rather than when ALL requests have finished using ajaxStop(). Maybe it will help, maybe not.
Related
I have a project which involves live notification. So I stumbled upon using socket io but I didn't have enough time to learn it yet. So I tried doing it with AJAX and jQuery. Below is my code structure and I was wondering if this is gonna work with no drawbacks?
setInterval(function(){
if( !element.hasClass('processing') ){
element.addClass('processing');
$.ajax({
type: 'post',
dataType: 'json',
url: ajaxurl,
data: {},
success: function( response ){
/* Success! */
element.removeClass('processing');
}
});
}
}, 2500);
Some Extra Info
The way you described will work. From Experience I would just like to point out some things.
I usually do a recursive function, allows you to wait your interval between ajax calls and not a fixed rate. //OPTIONAL BUT DOES GIVE THE SERVER SOME BREATHING ROOM.
Use window.setTimeout() with an isActive flag. //ALLOWS YOU TO STOP POLLING FOR WHATEVER REASON, AND BECAUSE FUNCTION IS RECURSIVE START UP AGAIN IF NEED BE
For Sake of being thorough, I found it is always a good idea to handle the error case of the $.ajax() post. You could perhaps display some message telling the user he is no longer connected to the internet etc.
Some Sample Code:
var isActive = true;
$().ready(function () {
//EITHER USE A GLOBAL VAR OR PLACE VAR IN HIDDEN FIELD
//IF FOR WHATEVER REASON YOU WANT TO STOP POLLING
pollServer();
});
function pollServer()
{
if (isActive)
{
window.setTimeout(function () {
$.ajax({
url: "...",
type: "POST",
success: function (result) {
//SUCCESS LOGIC
pollServer();
},
error: function () {
//ERROR HANDLING
pollServer();
}});
}, 2500);
}
}
NOTE
This is just some things I picked up using the exact method you are using, It seems that Web Sockets could be the better option and I will be diving into that in the near future.
Please refer :
Jquery : Ajax : How can I show loading dialog before start and close after close?
I hope this could help you
$("div.add_post a").click(function(){
var dlg = loadingDialog({modal : true, minHeight : 80, show : true});
dlg.dialog("show");
$.ajax({
url : "/add.php",
complete : function (){
dlg.dialog("hide");
}
});
return false;
});
//--Loading dialog
function loadingDialog(dOpts, text = "пожалуйста подождите, идет загрузка...")
{
var dlg = $("<div><img src='/theme/style/imgs/busy.gif' alt='загрузка'/> "+text+"<div>").dialog(dOpts);
$(".ui-dialog-titlebar").hide();
return dialog;
}
As my title indicates, I need to run a function if any ajax get/post is fired.
I tried using
$(document).ajaxStart(function () {
console.log('a');
});
$(document).ajaxComplete(function () {
console.log('c');
});
but it runs only for the first time.
Later it does not log anything. What am I doing wrong?
I need to do this in chrome extension and on google image search page, so after 100 images it fire a ajax function to get more image data and show on page.
You probably want it to work even if AJAX requests are not made with jQuery with a technique like How to check if HTTP requests are open in browser?
(function() {
var oldOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
console.log('Request went out', arguments);
oldOpen.call(this, method, url, async, user, pass);
}
})();
You might be looking for something like this:
$.ajaxSetup({
success: function(){
callYourFunctionHere();
}
});
OR
$(document).bind("ajaxSend", function(){
alert('ajax fired');
callYourFunctionHere();
});
Hope it works for you.
The ajax method itself can accept functions in beforeSend and complete.
.ajax({
// the rest of your parameters
complete: function(data) {
// do something
}
});
If you do not want to specify these on a per-request basis, you can do so with the `.ajaxSetup' function which modifies the defaults.
.ajaxSetup({
beforeSend: function() {
// custom logic
},
complete: function() {
// custom logic
}
});
I am making few ajax requests in my jQuery file. On success of these jQuery requests, I wrote few on click events which are not working.
This is my code
$(document).ready(function (){
$.ajax ({
type: "POST",
url: 'myServlet',
async: false,
success: function (response) {
id = parseInt(response);
setOutputEvents();
}
});
function setOutputEvents() {
for (var queryNumber = 0; queryNumber <= id; queryNumber++) {
$.ajax({
type: "POST",
url: 'myOtherServlet',
data: {queryNumber: queryNumber},
success: success,
async: false
});
var success = function (response) {
//some code here
generateTable();
}
}
}
function generateTable () {
//some code here
pagination();
}
function pagination(){
$(".class").click(function(event) {
alert();
});
}
$("#me").on("click", function(){
alert("me is triggered");
});
});
I understand making multiple ajax requests is a bad programming practice but what could be the reason for on click events not getting triggered?
These are the onclick events which are not working.
function pagination(){
$(".class").click(function(event) {
alert();
});
}
$("#me").on("click", function(){
alert("me is triggered");
});
I am using Google Chrome Version 39.0.2171.95 on Windows 7.
Please do let me know if any further information is necessary.
Since you use ajax to load even the initial content it seems, .class / #me html elements likely do not exist on initial page load of the DOM. As you didn't post html, i'm guessing this is the case.
Thus, you need to use a delegated event click handler to respond to it
so, you would change
$("#me").on("click", function(){
to
$(document).on("click", "#me", function(){
and so forth to link it to the parent element that does exist, the document itself.
This would work:
$(".class").on("click", function(){
alert("me is triggered");
});
function generateTable () {
//some code here
pagination();
}
function pagination(){
$(".class").trigger("click");
}
Some notes:
Event handler must be registered before triggering click.
Triggered click selector must match the class which has the click event registered.
Functions must be defined before the usage.
Hello guys here's my code:
var ajax={
chiamata:function(target,url,opzioni){
if (!tools.array_key_exists('caricamento',opzioni)){
opzioni['caricamento']=1;
}
var dati=url.split('?');
$.ajax({
type: opzioni['type'],
url: url,
contentType:"application/x-www-form-urlencoded; charset=UTF-8",
data: dati[1],
dataType: "html",
success: function(msg){
if (opzioni['caricamento']!=0){
ajax.printLoading();
}
$(target).html(msg);
},
error: function(){
alert("Chiamata fallita!");
}
})
},
printLoading:function(){
var body="#colonnaDX";
$(body).ajaxStart(function(){
$(body).append('<div id="loading"><img src="graphic/IMAGE/spinner.gif"/>Loading...</div>');
})
.ajaxStop(function(){
$('#loading').remove();
});
}
},
//Recursive function
var object={
checkAzione:function(target,url,opzioni,interval){
if (!interval)
interval=60000;
ajax.chiamata(target,url,opzioni);
setTimeout(function() {
this.checkAzione(target,url,opzioni,interval);
}, interval);
}
}
$(document).ready(function(){
object.checkAzione(
'#colonnaDX',
'someactions.php',{
'caricamento':0
},
10000
);
})
I'll try to explain the problem as better as i can, When the document is ready, the function "checkAzione" starts and it makes some stuff like DB calls etc, this kinds of ajax calls don't need any visual loading like spinner etc so in the array "opzioni" i set a flag 'caricamento':0 (same of 'loading':0) just check my ajax object to see what i mean, it works until i make some ajax calls that using 'caricamento':1, from that moment every ajax calls in my recursive function makes the "printLoading"... Any tips????
ajaxStart and ajaxStop are global, you add them to the body. You probably shouldn't use ajaxStart/Stop in this case, just add the functionality to your ajax listeners (success and error).
Something in my script is breaking IE.
I'm looking on a collection of links with a class, and hijacking the URL's.
Clicking a link will animate the height and reveal a message. It also
does an ajax request to mark the message as read.
However, in IE it simply goes to the URL instead of staying on the page and processing the http request.
$('.message .subject .subject_link').click(function(e) {
toggle_message(e)
return false;
});
function toggle_message(m) {
var link = m.target;
var parent = $(link).parent().parent();
console.log(link.href);
$.ajaxSetup({
url: link.href,
dataType: 'json',
timeout: 63000,
type: 'GET',
cache: false
});
if($(parent).hasClass('unread')) {
$(parent).addClass('read').removeClass('unread');
$.ajax({
complete: function(r, textStatus) {
console.log(r.responseText)
}
});
}
if($(parent).find('.body_wrapper').hasClass('collapsed')) {
$(parent).find('.body_wrapper').addClass('expanded').removeClass('collapsed');
$(parent).find('.body_wrapper').animate({
height: 'toggle'
})
} else {
$(parent).find('.body_wrapper').addClass('collapsed').removeClass('expanded');
$(parent).find('.body_wrapper').animate({
height: 'toggle'
})
}
}
any ideas what's causing this issue?
http://support.cooper.krd-design.net/
tester: 12345 if you want to review the page
Thanks
Rich
Adding
e.preventDefault();
before toggle_message in the first function should work, although return false should as well.
I don't have access to IE right now but I think you could try preventing the default click event to fire in your click()-function like so:
$('.message .subject .subject_link').click(function(e) {
toggle_message(e)
e.preventDefault();
});
More on .preventDefault() here: http://api.jquery.com/event.preventDefault/