I am using .ajaxStart() and .ajaxStop() to show a modal while an ajax request is being made. (between start and stop)
Now I'd like to add a longpoll function that keeps waiting for notifications, similar to the one on the left upper corner of this site.
My problem now lies in disabling this modal only for the longpolling request..
Registering "loading screen" on and off handlers:
$(document).ajaxStart(handleAjaxStart);
$(document).ajaxStop(handleAjaxStop);
My longpoll function:
$.ajax({
timeout: 35000,
url: longPollUrl,
success: function(data){
if(data.queCount) $('#numQueCount').html(data.queCount);
if(data.queAccept) $('#numQueAccept').html(data.queAccept);
},
dataType: 'json',
complete: longpoll
});
I tried:
$().off('ajaxStart');
$().off('ajaxStop');
..and reattaching the handlers after starting the polling, but no joy.
I also tried introducing a global variable into handleAjaxStart() that would return at the first line of the function, but that seems to completely kill the loading screen.
Any ideas how this can be achieved?
I figured it out..
There is an attribute in the options object .ajax() takes called global.
If set to false, it will not trigger the ajaxStart event for the call.
$.ajax({
timeout: 35000,
url: longPollUrl,
success: function(data){
if(data.queCount) $('#numQueCount').html(data.queCount);
if(data.queAccept) $('#numQueAccept').html(data.queAccept);
},
global: false, // this makes sure ajaxStart is not triggered
dataType: 'json',
complete: longpoll
});
After reading all possible solutions, I want to combine answers.
Solution 1: Bind/Unbind
//binding
$(document).bind("ajaxStart.mine", function() {
$('#ajaxProgress').show();
});
$(document).bind("ajaxStop.mine", function() {
$('#ajaxProgress').hide();
});
//Unbinding
$(document).unbind(".mine");
It is a depreciated solution. Before jQuery 1.9, global events of ajax like ajaxStart, ajaxStop, ajaxError etc. can be binded to any element. After jQuery 1.9:
As of jQuery 1.9, all the handlers for the jQuery global Ajax events,
including those added with the .ajaxStart() method, must be attached
to document.
Therefore we cannot bind/unbind these events to custom namespaces.
Solution 2: Set the property global to false
$.ajax({
url: "google.com",
type: "GET",
dataType: "json",
global: false, //This is the key property.
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
This solution works to disable ajaxStart()/ajaxStop() event(s). However, it also makes disable ajaxComplete(), ajaxError(), ajaxSend(), ajaxSuccess(). If you don't use these global events, it seems ok, but when it is needed, you have to come back and change your solution for all pages where you set global: false.
Solution 3: Use global variable
var showLoadingEnabled = true;
$(document).ready(function () {
$('#loading')
.hide() // at first, just hide it
.ajaxStart(function () {
if (showLoadingEnabled) {
$(this).show();
}
})
.ajaxStop(function () {
if (showLoadingEnabled) {
$(this).hide();
}
});
});
function justAnotherFunction() {
window.showLoadingEnabled = false;
$.ajax({
url: 'www.google.com',
type: 'GET',
complete: function (data) {
window.showLoadingEnabled = true;
console.log(data);
}
});
}
Global variables should not be used in javascript files. However, this is the simplest solution, I can find.
I prefered the third solution for my project.
Related
I have this jquery ajax call that is trigger on keyup. It has error handling which (with Firefox for e.g.) is triggered multiples times if the user enters keystrokes fast. Is there a quick way to stop multiple alert windows to be shown?
$('input[name$="_LOC"]').keyup(function(){
if ($(this).val().length >=4){
$.ajax({
type: 'POST',
url: 'red.asp?q='+$(this).val(),
beforeSend: function() {
[...]
},
success: function(data) {
[...]
},
error: function() {
alert("Oops!")
}
});
}
});
Restart a timer each time the onkeyup is triggered, this means the event only happens when the user has finished typing (or, at least, paused for a second or whatever).
Use timer = setTimeout(yourFunction, yourDelay);
To rest the timer user clearInterval(timer) and start the setTimeout again.
var typing = false;
var timer;
$('input[name$="_LOC"]').keyup(function(){
if(typing) {
clearInterval(timer);
}
timer = setTimeout(sendAjax, 500, [this]);
typing=true;
});
function sendAjax(element)
{
if ($(element).val().length >=4){
$.ajax({
type: 'POST',
url: 'red.asp?q='+$(element).val(),
beforeSend: function() {
[...]
},
success: function(data) {
[...]
},
error: function() {
alert("Oops!")
}
});
typing = false;
}
Here's JSFiddle example: http://jsfiddle.net/X8US5/, you'll need your browsers console.log viewer ready to see stuff (otherwise edit the console.logs to be alerts though they interrupt JS so times will be off)
Edit:
IE9 compatible (hack) version http://jsfiddle.net/5ndM5/1/
Tried to find a jQuery alternative but none it seems.
THe overriding the function alternative is good if you don't want the global var, but if you only plan to use this code on one form then the global is acceptable (JS code is usually rife with them by accident anyway)
function bindALLFunctions() {
..all triggers functions related go here
};
$.ajax({
type: 'POST',
url: myURL,
data: { thisParamIdNo: thisIdNo },
success: function(data){
$(".incContainer").html(data);
bindALLFunctions();
},
dataType: 'html'
});
I am new to ajax and JQuery.
I have the above ajax call in my js-jquery code. bindALLFunctions(); is used to re-call all the triggers and functions after the ajax call. It works all fine and good as expected. However, I have read somewhere that is better to load something after the initial action is finished, so I have tried to add/edit the following two without any success.
Any ideas?
1) -> $(".incContainer").html(data, function(){
bindALLFunctions();
});
2) -> $(".incContainer").html(data).bindALLFunctions();
Perhaps you should have a look to the live and delegate functions. You can set a unique event handler at the beggining of your app and all your loaded ajax code will be automatically binded:
$("table").delegate("td", "hover", function(){
$(this).toggleClass("hover");
});
But if you prefer to use Jquery.ajax call you have to do something like this:
$.ajax({
type: 'POST',
url: myURL,
data: { thisParamIdNo: thisIdNo },
success: function(data){
$(".incContainer").html(data);
bindALLFunctions(".incContainer");
},
dataType: 'html'
});
and transform bindALLFunctions as:
function bindALLFunctions(selector) {
..all triggers functions related go here. Example:
$('#foo', selector).bind('click', function() {
alert('User clicked on "foo."');
});
};
that will only bind events "under" the given selector.
Your initial code was fine. The new version does not work because html() function does not have a callback function.
It's hard to tell from your question just what you intend to ask, but my guess is that you want to know about the ready function. It would let you call your bindALLFunctions after the document was available; just do $(document).ready(bindALLFunctions) or $(document).ready(function() { bindALLFunctions(); }).
If I call a function to load my grid data, loadComplete does not fire. I need to handle this event so I can manually update multiselect checkbox correctly. If I update in gridComplete, I have to click the checkbox twice to uncheck it.
In your previous question you wrote that you use WCF on the server side. In the case you don't need to use datatype as function. Instead of that you can just use the following parameters:
datatype: "json",
ajaxGridOptions: { contentType: "application/json" },
serializeGridData: function (data) {
return JSON.stringify(data);
}
To be sure that JSON.stringify are supported in old web browsers you should include json2.js which you can load from here.
In the old answer you can find more code examples (and download the demo) which shows how you can use WCF with jqGrid.
Now I will answer on your original question: "Why loadComplete does not fire" if you use datatype as function. The short answer is: if you use datatype as function your code is responsible for calling of loadComplete.
If you use datatype as function your code is responsible to some things which jqGrid do typically. So first of all you have to understand what should the datatype function do. An example from the documentation (see here) shows the simplest, but not full, implementation of datatype as function. More full code example looks like the following:
$("#list").jqGrid({
url: "example.php",
mtype: "GET",
datatype: function (postdata, loadDivSelector) {
var ts = this, // cache 'this' to use later in the complete callback
p = this.p; // cache the grid parameters
$.ajax({
url: p.url,
type: p.mtype,
dataType: "json",
contentType: "application/json",
data: JSON.stringify(postdata),
cache: p.mtype.toUpperCase() !== "GET",
beforeSend: function (jqXHR) {
// show the loading div
$($.jgrid.jqID(loadDivSelector)).show();
// if loadBeforeSend defined in the jqGrid call it
if ($.isFunction(p.loadBeforeSend)) {
p.loadBeforeSend.call(ts, jqXHR);
}
},
complete: function () {
// hide the loading div
$($.jgrid.jqID(loadDivSelector)).hide();
},
success: function (data, textStatus, jqXHR) {
ts.addJSONData(data);
// call loadComplete
if ($.isFunction(p.loadComplete)) {
p.loadComplete.call(ts, data);
}
// change datatype to "local" to support
// "loadonce: true" or "treeGrid: true" parameters
if (p.loadonce || p.treeGrid) {
p.datatype = "local";
}
},
error: function (jqXHR, textStatus, errorThrown) {
if ($.isFunction(p.loadError)) {
p.loadError.call(ts, jqXHR, textStatus, errorThrown);
}
});
},
... // other parameters
});
You can see that the code in not so short. In the above example we still not support some jqGrid options like virtual scrolling (scroll: 1 or scroll: true).
Nevertheless I hope that I cleared now why I don't recommend to use datatype as function. If you use it you have to understand many things how jqGrid work internally. You should examine it's source code to be sure that you do all things correctly. If you skip somethings, than your code will works incorrect in some situations or in some combination of jqGrid parameters.
If you look at the code which I included at the beginning of my answer (the usage of ajaxGridOptions and serializeGridData) you will see that the code is very easy. Moreover it works with all other legal combination of jqGrid parameters. For example you can use loadonce: true, loadComplete, loadError or even virtual scrolling (scroll: 1 or scroll: true). All things needed depend on the parameters do jqGrid for you.
I'm trying to disable a button after it's clicked. I have tried:
$("#ajaxStart").click(function() {
$("#ajaxStart").attr("disabled", true);
$.ajax({
url: 'http://localhost:8080/jQueryTest/test.json',
data: {
action: 'viewRekonInfo'
},
type: 'post',
success: function(response){
//success process here
$("#alertContainer").delay(1000).fadeOut(800);
},
error: errorhandler,
dataType: 'json'
});
$("#ajaxStart").attr("disabled", false);
});
but the button is not getting disabled. When I remove $("#ajaxStart").attr("disabled", false); the button gets disabled.
While this is not working as expected, I think the code sequence is correct. Any help will be appreciated.
Put $("#ajaxStart").attr("disabled", false); inside the success function:
$("#ajaxStart").click(function() {
$("#ajaxStart").attr("disabled", true);
$.ajax({
url: 'http://localhost:8080/jQueryTest/test.json',
data: {
action: 'viewRekonInfo'
},
type: 'post',
success: function(response){
//success process here
$("#alertContainer").delay(1000).fadeOut(800);
$("#ajaxStart").attr("disabled", false);
},
error: errorhandler,
dataType: 'json'
});
});
This will ensure that disable is set to false after the data has loaded... Currently you disable and enable the button in the same click function, ie at the same time.
In your code, you just disable & enable the button on the same button click,.
You have to enable it inside the completion of AJAX call
something like this
success: function(response){
$("#ajaxStart").attr("disabled", false);
//success process here
$("#alertContainer").delay(1000).fadeOut(800);
},
I have solved this by defining two jquery functions:
var showDisableLayer = function() {
$('<div id="loading" style="position:fixed; z-index: 2147483647; top:0; left:0; background-color: white; opacity:0.0;filter:alpha(opacity=0);"></div>').appendTo(document.body);
$("#loading").height($(document).height());
$("#loading").width($(document).width());
};
var hideDisableLayer = function() {
$("#loading").remove();
};
The first function creates a layer on top of everything. The reason the layer is white and completely opaque, is that otherwise, IE allows you to click through it.
When doing my ajax, i do like this:
$("#ajaxStart").click(function() {
showDisableLayer(); // Show the layer of glass.
$.ajax({
url: 'http://localhost:8080/jQueryTest/test.json',
data: {
action: 'viewRekonInfo'
},
type: 'post',
success: function(response){
//success process here
$("#alertContainer").delay(1000).fadeOut(800);
hideDisableLayer(); // Hides the layer of glass.
},
error: errorhandler,
dataType: 'json'
});
});
I solved this by using global function of ajax
$(document).ajaxStart(function () {
$("#btnSubmit").attr("disabled", true);
});
$(document).ajaxComplete(function () {
$("#btnSubmit").attr("disabled", false);
});
here is documentation link.
The $.ajax() call "will not block" -- that means it will return immediately, and then you enable the button immediately, so the button is not disabled.
You can enable the button when the AJAX is successful, has error, or is otherwise finished, by using complete: http://api.jquery.com/jQuery.ajax/
complete(XMLHttpRequest,
textStatus)
A function to be
called when the request finishes
(after success and error callbacks are
executed). The function gets passed
two arguments: The XMLHttpRequest
object and a string categorizing the
status of the request ("success",
"notmodified", "error", "timeout", or
"parsererror"). This is an Ajax Event.
I have the following script which works perfectly until I regenerate the links ".resultLink" via jquery ajax:
$("a.resultLink").live('click', function()
{
var that = this;
$.ajax({
url: 'most_used.aspx',
type: 'POST',
data: { strMostUsedID:$(that).attr("href") },
error: function() { },
success: function() { }
});
});
"live" normally fixes this for me but this time it did not. Not sure what I am doing wrong.
The most likely cause I can think of is the selector not matching, double check that the .resultLink class is being applied to the new links...if it's not the .live() handler won't match the selector.