How to get HTTP-StatusCode in ajaxError? - javascript

I try to get the HTTP error code in the generic $(document).ajaxError() method. How can I read it out? I found this jQuery: How to get the HTTP status code from within the $.ajax.error method? but I don't manage to adapt it to my function.
JQuery version is 2.1.3.
$(document).ajaxError(function (jqXHR, textStatus, errorThrown) {
if (jqXHR.statusCode != "500") {
$("#global-error-wrapper").show();
$(".global-error-message-inner-text").text(trans("noconnectionerror"));
}
});

You are using ajaxError which seems to be a bit different than the ajax event error handler defined in the settings in the link you posted. For ajaxError(), it looks like the first parameter in the callback is the event and the second is the jqXHR object you want. Also it should be jqXHR.status and not statusCode Try the below
$(document).ajaxError(function (event, jqXHR, settings, thrownError) {
if (jqXHR.status != 500) {
$("#global-error-wrapper").show();
$(".global-error-message-inner-text").text(trans("noconnectionerror"));
}
});

The statusCode object on the jqXHR object in your ajaxError method refers to an object mapping that you can create when you build your ajax call. If you have an idea of what status codes to expect, you could build out this mapping and send it along with your ajax calls which could help you identify what status code was returned:
var statusCodeMapping = {
404: function() {
$notFound = true;
}
}
$.ajax({
statusCode: statusCodeMapping
});
You could then examine the $notFound object to see if that was the status code returned from your Ajax call:
$(document).ajaxError(function (jqXHR, textStatus, errorThrown) {
if ($notFound) {
$("#global-error-wrapper").show();
$(".global-error-message-inner-text").text(trans("noconnectionerror"));
}
});
The $notFound object should be global to your script

Related

Execute a callback when any ajax request is done on my page

I have a js file (using jQuery) that am making ajax request. The thing is that i want to redirect to 'login' whenever the error.status == 401 (Unauthorized), but i dont want to do this everywhere there is an ajax call.
error: function(e){
if(e.status == 401){
notice(e.responseText+' Please Login.', 'error');
}
}
Define a new function that does what you want and call it inside the error callback:
var errorFunction = function(responsetext) {
notice(responsetext +' Please Login.', 'error');
}
then:
error: function(e){
if(e.status == 401){
errorFunction(e.responseText);
}
}
You can use global ajaxError() and define conditions within it based on settings like url or special properties you can assign to any xhr object within specific requests in beforeSend callback
Example modified from ajaxerror() docs
$( document ).ajaxError(function( event, jqxhr, settings, thrownError ) {
if ( settings.url == "ajax/missing.html" ) {
$( "div.log" ).text( "Triggered ajaxError handler." );
// do a redirect
window.location = '/path/to/login';
}
});

Ajax not loading in IE

Here is the script. It works fine in all other browsers, so I thought it was a cache problem but not really. I have been banging my head for hours and nothing is working.
$.ajaxSetup({
cache: false
});
$("#send").live('click', function () {
console.log("AAAAA");
$("#loader").show();
$form = $('#reservationForm');
$inputs = $form.find('input[name^="entry"]'),
serializedData = $('#reservationForm :input[name^="entry"]').serialize();
console.log(serializedData);
serializedData += "&pageNumber=0&backupCache=1&submit=Submit";
// fire off the request to /form.php
$.ajax({
url: "https://docs.google.com/spreadsheet/formResponse?formkey=d",
// url: "https://docs.google.com/spreadsheet/formResponse?formkey=d;ifq",
type: "post",
data: serializedData,
// callback handler that will be called on success
success: function (response, textStatus, jqXHR) {
// log a message to the console
console.log("Hooray, it worked!");
$("#loader").hide();
document.getElementById('error<?php echo"$uname";?>').innerHTML = error;
$("#success").fadeIn();
setTimeout(function () {
$("#success").fadeOut();
}, 5000);
},
// callback handler that will be called on error
error: function (jqXHR, textStatus, errorThrown) {
// log the error to the console
console.log("The following error occured: " + textStatus, errorThrown);
alert('Due to an unknown error, your form was not submitted, please resubmit it or try later.');
},
// callback handler that will be called on completion
// which means, either on success or error
complete: function () {
// enable the inputs
$inputs.removeAttr("disabled");
}
});
// prevent default posting of form
event.preventDefault();
});
console.log is available after you open Developer Tools (F12 to open) in IE. Try turning it on or use an alert instead in your code.
or use a try catch;
try{
console.log('worked')
}
catch(err){
}
And You might want to check if your event variable is undefined:
event= event || window.event;
event.preventDefault();
At the beginning of the script you are not adding the "event" declaration in the handler:
$("#send").live('click', function () {
should be:
$("#send").live('click', function (e) {
And at the end of the script there is a reference for the variable event:
// prevent default posting of form
event.preventDefault();
I think that IE doesn't have a 'preventDefualt' function in the global event object (which you are referencing): this function is added to the "e" event object passed by jQuery. Any way, it should fail too in all other browsers with a "event is not defined". Try this too:
// prevent default posting of form
e.preventDefault();
An additional note: jQuery team currently discourage the use of the "live" event binding function, instead you should use the equivalent form of the "on" function.
IE doesn't understand the content type of response in ajax. So put your dataType value in the request and it should work.
for e.g. -
dataType: ($.browser.msie) ? "text" : "xml"

jquery.validate plugin accessing the form in ajax success callback

I'm confused on how to access the submitted form using the jQuery.validate plugin.
In the "success" option of the API options: http://jquery.malsup.com/form/#options-object
it says that the 4th parameter in the success function is the jquery wrapped form object but my attempts to access it with jQuery keep saying its undefined.
here's how the success function looks on their examples page: http://jquery.malsup.com/form/#ajaxSubmit
function showResponse(responseText, statusText, xhr, $form) {
var id=$form.attr('id');
console.log('id:'+id);
}
unfortunately, console.log says Uncaught TypeError: Cannot call method 'attr' of undefined.
any thoughts?
thanks,
tim
the variable cannot start with $ I suppose. Remove the $ and try again?
function showResponse(responseText, statusText, xhr, form) {
var id = form.attr('id');
console.log('id:'+id);
}
Or this might be another solution, if not a jQuery object:
function showResponse(responseText, statusText, xhr, form) {
var id = $(form).attr('id');
console.log('id:'+id);
}
Other possibilities
function showResponse(responseText, statusText, xhr, form) {
var id = $(form).attr('id');
console.log('id:'+id);
}
function showResponse(responseText, statusText, xhr, form) {
var id = form.attr('id');
console.log('id:'+id);
}
function showResponse(responseText, statusText, xhr, $form) { // Won't work
var id = form.attr('id');
console.log('id:'+id);
}
function showResponse(responseText, statusText, xhr, $form) { // High chance
var id = $($form).attr('id');
console.log('id:'+id);
}
Hope this helps! :)
I solved this problem by explicitly writing out the jQuery form selector every time and not trying to pass it as an object.
So rather than trying to pass around $form I used this:
$('#myForm').attr(...)
It is more verbose but at least it works!

help with jquery ajax success event

I'm having an issue with my update button and jquery ajax. Right now when I click on my update button, it saves whatever updated data to the database. My goal is I want to slide up a message if the update is successful. I was looking at ajax post and using the success event seems like it would work but I dont know how to incorporte it. How would I do this? Would it be something like this?
$(document).ready(function(){
$('#divSuccess').hide();
$('#btnUpdate').click( function() {
alert('button click');
$.ajax({
url: "test.aspx",
context: document.body,
success: function(){
$('#divSuccess').show("slide", { direction: "down" }, 3000);
$('#divSuccess').hide("slide", { direction: "down"}, 5000);
}
});
});
});
check out this question for an example on how to handle the success event. Hope this helps!
$("#targetDiv").load("page.php",$("#form").serializeArray(),function (response)
{
if (response == '0' && response != '')
alert('Request not sent to server !\n');
else if(response == '-1')
alert('Please write some more !\n');
else
{
alert("success! ");
}
}
);
i've echo ed 0 and -1 for failure and other for success
In the jquery post function, you can execute some callback function.
function (data, textStatus) {
// data could be xmlDoc, jsonObj, html, text, etc...
this; // the options for this ajax request
// textStatus can be one of:
// "timeout"
// "error"
// "notmodified"
// "success"
// "parsererror"
// NOTE: Apparently, only "success" is returned when you make
// an Ajax call in this way. Other errors silently fail.
// See above note about using $.ajax.
}
http://docs.jquery.com/Post
With at least jQuery 1.5, you've got deferred objects and new syntax for AJAX events (including success).
var $ajaxcall = $.ajax({
url : 'myurl.svc/somemethod',
data : '{ somedata : "sometext" }'
});
$ajaxcall.success(function() {
// do something on successful AJAX completion
});
Of course you can chain that as well, and call something along the lines of $.ajax().success() or something.
Just wrote a blog post on it myself, if you're interested in reading more.

Abort all jQuery AJAX requests globally

Is there a way to abort all Ajax requests globally without a handle on the request object?
The reason I ask is that we have quite a complex application where we are running a number of different Ajax requests in the background by using setTimeOut(). If the user clicks a certain button we need to halt all ongoing requests.
You need to call abort() method:
var request = $.ajax({
type: 'POST',
url: 'someurl',
success: function(result){..........}
});
After that you can abort the request:
request.abort();
This way you need to create a variable for your ajax request and then you can use the abort method on that to abort the request any time.
Also have a look at:
Aborting Ajax
You cannot abort all active Ajax requests if you are not tracking the handles to them.
But if you are tracking it, then yes you can do it, by looping through your handlers and calling .abort() on each one.
You can use this script:
// $.xhrPool and $.ajaxSetup are the solution
$.xhrPool = [];
$.xhrPool.abortAll = function() {
$(this).each(function(idx, jqXHR) {
jqXHR.abort();
});
$.xhrPool = [];
};
$.ajaxSetup({
beforeSend: function(jqXHR) {
$.xhrPool.push(jqXHR);
},
complete: function(jqXHR) {
var index = $.xhrPool.indexOf(jqXHR);
if (index > -1) {
$.xhrPool.splice(index, 1);
}
}
});
Check the result at http://jsfiddle.net/s4pbn/3/.
This answer to a related question is what worked for me:
https://stackoverflow.com/a/10701856/5114
Note the first line where the #grr says: "Using ajaxSetup is not correct"
You can adapt his answer to add your own function to window if you want to call it yourself rather than use window.onbeforeunload as they do.
// Most of this is copied from #grr verbatim:
(function($) {
var xhrPool = [];
$(document).ajaxSend(function(e, jqXHR, options){
xhrPool.push(jqXHR);
});
$(document).ajaxComplete(function(e, jqXHR, options) {
xhrPool = $.grep(xhrPool, function(x){return x!=jqXHR});
});
// I changed the name of the abort function here:
window.abortAllMyAjaxRequests = function() {
$.each(xhrPool, function(idx, jqXHR) {
jqXHR.abort();
});
};
})(jQuery);
Then you can call window.abortAllMyAjaxRequests(); to abort them all. Make sure you add a .fail(jqXHRFailCallback) to your ajax requests. The callback will get 'abort' as textStatus so you know what happened:
function jqXHRFailCallback(jqXHR, textStatus){
// textStatus === 'abort'
}

Categories

Resources