Please check: http://jsfiddle.net/TWiStErRob/s2jSA/ where I try set up all possible variations I could think of for:
success, error, complete
ajaxSetup
ajaxSuccess, ajaxError, ajaxComplete
done, fail, always
As I see:
a lot of events are missing for JSONP
I would expect the same output as for JSON
Global AJAX events don't work as the Deferred's callbacks, i.e. registration order matters, but only with the same type of events.
Not a biggie, I can live with it.
complete is running after success/error
Good to know.
It seems that for JSONP the events are almost useless, can someone please explain why and give a workaround?
Reason
From http://api.jquery.com/category/ajax/global-ajax-event-handlers/
Note: Global events are never fired for cross-domain script or JSONP requests, regardless of the value of global.
From http://bugs.jquery.com/ticket/8338
JSONP requests are not guaranteed to complete (because errors are not caught). jQuery 1.5 forces the global option to false in that case so that the internal ajax request counter is guaranteed to get back to zero at one point or another.
If you want all requests to fire the events, no matter what (and at the risk of the same inconsistencies 1.4.4 exhibited), you can use the following prefilter:
jQuery.ajaxPrefilter(function( options ) {
options.global = true;
});
Workaround
The above code indeed makes it work:
$.ajaxPrefilter(function global_ajaxPrefilter(options, originalOptions, jqXHR) {
options.global = true;
});
$(document).ajaxSuccess(function global_ajaxSuccess(event, XMLHttpRequest, ajaxOptions) {
if(config.logResponses) {
console.log(XMLHttpRequest.responseText);
}
});
$(document).ajaxError(function global_ajaxError(event, jqXHR, ajaxSettings, thrownError) {
console.error("error: " + jqXHR.status + " " + thrownError);
});
However for my purposes the following approach works better:
$.ajaxPrefilter(/*dataTypes, */ function global_ajaxPrefilter(options, originalOptions, jqXHR) {
if(config.logResponses) {
jqXHR.done(function global_ajaxSuccess(data, textStatus, jqXHR) {
console.groupCollapsed(options.url + (options.data ? '&' + $.param(options.data) : ''));
console.log("Options: " + JSON.stringify(options));
console.log("Data: " + JSON.stringify(data));
console.groupEnd();
});
}
jqXHR.fail(function global_ajaxError(jqXHR, textStatus, errorThrown) {
console.error(textStatus + ": " + errorThrown));
});
});
Notice the different argument list of global_ajaxSuccess and global_ajaxError:
options: available in both solutions (contains URL)
data: is available as text in global handler, and object in done
interface is much familiar with done/error
Related
I'm using WebvoltyTemplate that utilizes it's own search template but it also is responsible for filtering products. Every time I try to search for a product in main searchbar and also when I try to show filter list with a simple button it uses ajax request. The problem is that every time it throws an error.
POST https://www.example.com/modules/wtcmssearch/ajax.php? 403
send # core.js:39
ajax # core.js:39
error wtcmssearch.js:62 error
The 'error' message comes from that part of code that doesn't actually tell anything.
$(document).on('keyup','.wtcmsheader-search .wtsearch-header-display-wrappper .wtheader-top-search .wtheader-top-search-wrapper-info-box .wtcmssearch-words',function(){
var obj = $(this).parent().parent().parent().parent().find('.wtsearch-result');
obj.html('');
obj.show();
var search_words = $(this).val();
var cat_id = $('.wtcms-select-category').find('.selected').val();
if (search_words.length != 0) {
$.ajax({
type: 'POST',
url: baseDir + 'modules/wtcmssearch/ajax.php?',
cache: false,
data: 'search_words='+ search_words + '&category_id='+ cat_id +' &token=' + static_token,
success: function(data)
{
obj.html('');
obj.append(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
});
The core.js function that throws an error is a very long one-liner:
function(e){var t,n,r,i,o,a,s,u,l,c,d,f,p,h,v,m,g,y,x,b="sizzle"+1*new Date,w=e.document,T=0,C=0,k=oe(),S=oe(),j=oe(),_=function(e,t){return e== .....................
Every file has right permissions set. I have no idea where should I start looking for a problem root. Any idea?
EDIT:
I have found out that another feature doesn't work because of that- adding to wishlist. It Also throws an error in core.js:39. I would like to send the whole line but it's about 83k characters.
EDIT 2:
I noticed that when I try to look up the ajax.php file through my browser it also throws an 403 exception. No idea how to investigate further. I turned of apache mod_security, didn't help.
While delete a comment, I can delete two comments back to back but when I tried to delete next comment(3rd comment). It shows error in console “Rate limited due to excessive requests.” But after few seconds when I try to delete, it works fine for next two comments. I have tried to use “wait” function for few seconds to make it work but there is inconsistency in result. Sometimes it works and sometimes it doesn’t.
My code as follows,
function deleteComment(MessagePostId) {
var result = confirm("Are you sure you want to delete this Comment?");
if (result) {
yam.platform.request({
url: "https://api.yammer.com/api/v1/messages/" + MessagePostId,
method: "DELETE",
async: false,
beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', token) },
success: function (res) {
alert("The Comment has been deleted.");
//Code to remove item from array and display rest of the comment to screen
},
error: function (res) {
alert("Please try again after some time.");
}
})
}
}
You are hitting rate limits which prevent multiple deletion requests from a regular user like those which you've hit. The API is designed for client applications where you perhaps make an occasional deletion, but aren't deleting in bulk.
To handle rate limits, you need to update your code to check the response value in the res variable. If it's an HTTP 429 response then you are being rate limited and need to wait before retrying the original request.
I'm making a functional mockup using mootools,and in this prototype I have to load an html file via request.HTML, but as soon as I run the script, the call never reaches the onSuccess due to the state = 0.
The blame could be that the request is treated as a violation of the crossdomain.
So I was wondering if is out there a way to work it around?
this is the code I use for performing the request
req = new Request.HTML({
url: "detail.html",
onFailure: function(a) { console.log("iFailed: " + a); },
onSuccess: function(r3, rEls, rHTML, rJS) {
console.log("It worked!!");
},
onComplete: function() { console.log('completed'); }
}).send();
as I run this it always goes into the onFailure and in the onComplete without hitting the onSuccess.
I need this to work with safari, because the mock shall work on an iphone/ipad/ipod.
thx a ton
in the end I managed it bu injecting an iframe via js, instead of populating the div via ajax.
it's kind of lame and it sucks a lot, but at least it work and it's good for prototyping purposes.
I have wrote an ajax function and it partially works. Doesn't give any errors . but when i add alert to check my values it works completely . It renders the complete thing . Can any one tell me where did i do wrong in here
$.ajax({
type : "POST",
url : "/usermanageajax/",
data : 'key=' + key_value,
success : function (data) {
var element = users.salary[users.salary.length -1];
var hrs = users.hours[users.hours.length -1];
var html = "<span title=\"" + users.name + "\">Name \"" + users.desc(0,50) + "...\" "+ "has " + element + " of "+ hrs + "</span>";
// alert('*');
$('#title').html(html);
chart_s = draw_chart(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
The justification of this issue is that the alert call blocks the calling of the two next line. Seems that the browser needs some milliseconds to achieve something before performing the two next lines.
Try to call setTimeOut on the two other lines to be called after few milliseconds.
Again, what is the browser you are testing on?
The fact that it works with the alert indicates a race condition.
Try moving your code to a complete handler instead of a success handler. You can also check for success there.
I am displaying a graph using jQplot to monitor data.
To refresh the div holding the graph, I invoke an ajax call every 5 seconds (see JavaScript excerpt below).
On the server, a PHP script retrieves the data from a database.
On success, the ajax call is reinvoked after 5 seconds with a JavaScript setTimeout(ajax,5000).
On error, the ajax call is retried 10 times with setTimeout(ajax,5000) before displaying an error message.
Monitoring XHR learns that the browser crashes after approximately 200 requests.
As a temporary remedy, a location.reload() is issued after 50 iterations to prevent the browser from crashing.
This works, but is not an ideal situation.
Any better solution to this problem is very much appreciated.
Thanks and regards, JZB
function ajax() {
$.ajax({
cache: false,
url: 'monitor.php',
data : { x: id },
method: 'GET',
dataType: 'json',
success: onDataReceived,
error: onDataError
});
function onDataReceived(series) {
$('#chartdiv_bar').html('');
$.jqplot('chartdiv_bar', [series['initHits']], CreateOptions(series,'Inits'));
errorcount = 0;
setTimeout(ajax, 5000);
}
function onDataError(jqXHR, textStatus, errorThrown) {
errorcount++;
if (errorcount == 10) {
alert("No server response:\n\n" + textStatus + "\n" + errorThrown);
} else {
setTimeout(ajax, 5000);
}
}
}
Since you're re-calling ajax() after a good or fail ajax call, you're starting multiple timers. This is why your browser is crashing.
you may want to try to clear the current timer and then start the next timer
var t; //global
In each of your call back functions:
if(t)
clearTimeout(t);
t = setTimeout(ajax, 5000);
more info on timer here: w3 school
I removed the jqplot call as suggested and the problem disappeared.
Apparently jqplot is the culprit and I found numerous entries referring to jqPlot memory leaks.
I use jQuery 1.6.4 and installed jqPlot Charts version 1.0.0b2_r792 which supposedly addresses memory leak issues.
Furthermore, I replaced
$('#chartdiv_bar').html('');
with
$('#chartdiv_bar').empty();
Thank you for your support.