Using beforeSend and complete in every instance of ajaxForm globally - javascript

I am trying to use the beforeSend and complete functions on all ajaxForms in a project. I would like to do this without adding the exact bit a code all throughout the project.
I've been able to accomplish this with the below code on a per form basis.
beforeSend: function() {
$('.lightbox').append('<div id="page-loader" style="display:block"><div class="page-loader-overlay"></div><div class="page-loader-content-container"><div class="top-corners"><div></div></div><div class="middle"><div class="page-loader-content">Loading...</div></div><div class="bottom-corners"><div></div></div></div></div>');
},
complete: function(xhr) {
$('.lightbox#page-loader').remove()
},
I'd like to be able to put that code into one place that executes every time an ajaxForm is submitted. Is this possible?

$(function(){
$.ajaxSetup({
beforeSend: function() {
$('.lightbox').append('<div id="page-loader" style="display:block"><div class="page-loader-overlay"></div><div class="page-loader-content-container"><div class="top-corners"><div></div></div><div class="middle"><div class="page-loader-content">Loading...</div></div><div class="bottom-corners"><div></div></div></div></div>');
},
complete: function(xhr) {
$('.lightbox#page-loader').remove()
},
});
});
Please use the function ajaxsetup. When you do it this way it will be valid in all ajax functions.
Referrer : https://api.jquery.com/jQuery.ajaxSetup/

If anyone runs across a similar dilemma, this is what I came up with and it seems to do the trick. I haven't found any problems with this thus far.
// add loading masks on form submits
$( document ).ajaxSend(function() {
$('.lightbox').append('<div id="page-loader" style="display:block; z-index: 999"><div class="page-loader-overlay"></div><div class="page-loader-content-container"><div class="top-corners"><div></div></div><div class="middle"><div class="page-loader-content">Loading...</div></div><div class="bottom-corners"><div></div></div></div></div>');
});
$(document).ajaxSuccess(function() {
$('#page-loader').remove()
});

Related

What is the proper way of doing long polling using jQuery and AJAX

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;
}

AJAX, PHP, MySQL. (refreshing tables without blink)

I can't find a solution for this and I can't believe I can't find just one example!
Ok, I have a kind of monitory (PHP / MySQL), refreshed by Javascript. The thing is, that my script reload an entire php page, where I have the MySQL Querys. So, every reload I see a little blink, which is nothing else that the page loading.
This is what I have:
(function($) {
$(document).ready(function() {
$.ajaxSetup( {
cache: false,
beforeSend: function() {
$('#colas').hide();
$('#loading').show();
},
complete: function() {
$('#loading').hide();
$('#colas').show();
},
success: function() {
$('#loading').hide();
$('#colas').show();
}
});
var $colas = $("#colas");
$colas.load("panelColasRealtime.php");
var refreshId = setInterval(function() {
$colas.load('panelColasRealtime.php');
}, 8000);
});
})(jQuery);
I load "panelColasRealtime.php" right here:
<div id="colas"></div>
This is working, but I don't want this solution, I don't like that blink. I want to refresh the monitory without reload the php page, just the data.
I think that AJAX is my best choice, but I can't find any example.
Summarizing:
I would like a realtime monitory (every X secods) of my BD and show it .
If anyone has an example script I would really appreciated it.
if you just want to refresh the data here is a simple example which refreshes every 5 seconds
$(document).ready(function() {
loadData();
});
var loadData = function() {
$.ajax({
type: "GET",
url: "data_source_page.php",
dataType: "html",
success: function(response) {
$(".refresh").html(response);
setTimeout(loadData, 5000);
}
});
};
html
<div class="refresh"></div>

Why is ajaxStop() not firing in Internet Explorer?

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.

Ajax recursive function work strange

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).

What is the easiest/best way to show that an HTML element is AJAX Loading?

Sometimes in my application there are many elements loading so I want to show the typical AJAX spinner above the control (or DOM node) with it disabled.
What is the easiest/best way to do that?
Ideally I would like to:
$("#myelement").loading();
$("#myelement").finishloading();
Or even better being able to do AJAX requests directly with the element:
$("#myelement").post(url, params, myfunction);
Being #myelement a regular node or form input.
You could use beforeSend and complete callbacks:
$.ajax({
url: 'script.cgi',
type: 'POST',
beforeSend: function() {
$('.spinner').show();
},
complete: function() {
// will trigger even if request fails
$('.spinner').hide();
},
success: function(result) {
// todo: do something with the result
}
});
Since you're already using jQuery, you may want to look into BlockUI in conjunction with Darin Dimitrov's answer. I haven't used it yet myself as I just came across this today, but it looks decent.
If you're writing a semi-large-ish application and anticipate making many AJAX calls from different places in your code, I would suggest that you either add a layer of abstraction over $.ajax, or create a helper function to avoid having boiler plate for your UI indicator all over the place. This will help you out a lot should you ever need to change your indicator.
Abstraction method
var ajax = function(options) {
$.ajax($.extend(
{
beforeSend: function() {
$.blockUI();
},
complete: function() {
$.unblockUI();
}
},
options
));
};
ajax({
url: 'script.cgi',
type: 'POST',
success: function(result) {
// todo: do something with the result
});
Helper method
var ajaxSettings = function(options) {
return $.extend(
{
beforeSend: function() {
$.blockUI();
},
complete: function() {
$.unblockUI();
}
},
options
);
};
$.ajax(ajaxSettings({
url: 'script.cgi',
type: 'POST',
success: function(result) {
// todo: do something with the result
}
}));
Also, I wouldn't suggest overwriting the $.ajax method itself.
what i've done in the past is, on post pass the element id (a containing div) to a function which replaces it's inner HTML with a loading image, and then in the post back replace it's content again with the updated real content.
If you want to show the spinner every when an ajax call is in progress I think you should use ajaxStart and ajaxStop.
$("#spinner")
.ajaxStart(function(){$(this).show();})
.ajaxStop(function(){$(this).hide();});

Categories