JQuery catch any ajax error - javascript

i like to catch any ajax 401 Unauthorised exception, but do no like to change all my ajax queries. Is there a way to change it for any $.ajax call like (overwrite any error handler) ?

you can use the global ajax event handlers .ajaxError()
$( document ).ajaxError(function( event, jqxhr, settings, exception ) {
    if ( jqxhr.status== 401 ) {
        $( "div.log" ).text( "Triggered ajaxError handler." );
    }
});

You can do something like this:
$(function() {
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status === 401) {
alert('HTTP Error 401 Unauthorized.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
This will catch error in any of your ajax calls.

The $.ajaxSetup() function will allow you to specify global options for Ajax calls. Be careful however as other calls to ajaxSetup() will overwrite global options and specified local options to the ajax() method will override global settings.
Documentation

Try using .ajaxError() as a global method http://api.jquery.com/ajaxError/

To catch a 401 status code simply add
$.ajaxSetup({
statusCode: {
401: function(err){
console.log('Login Failed.', err.responseJSON);
// or whatever...
}
}
});
to your page somewhere before the AJAX call is fired.

Related

Sending an error in grails and reading it in Javascript

Hi my question is how i would send an error from the grails side after a check, for example in a grails controller being called if i had (don't know if its correct):
if(something){ return error #}
else if(something){ return error #}
else{ return error#}
And then what i would need to do in a js function so that it can receive said errors and then act upon it. ie. Error 200 continues as normal, error 400 renders a new page etc, just need to get to the part of reading this error.
Simple stuff:
def delPhoto() {
Photos ph = Photos.get(params.id as Long)
if (ph) {
doSomething()
// return status 200
render status:response.SC_OK
return
}
//OtherWise return 404
render status:response.SC_NOT_FOUND
}
Now in your gsp java script
$.ajax({timeout:1000,cache:true,type: 'GET',url: "${g.createLink(controller: 'photos', action: 'delPhoto')}",
success: function(data) {
$("#uploads").html(data);
},
statusCode: {
417: function() {
$('#field').css({'color':'white'});
$('#field').html("${g.message(code:'default.false.error')}")
}
},
statusCode: {
404: function() {
$('#field').css({'color':'white'});
$('#field').html("${g.message(code:'default.false.error')}")
}
},
error: function (e) {
}
});
});
So your ajax call then defines for each error message or success what things to update on the page
instead of returning status you can directly set your response status in you controller action like this
response.status = 401
and render anything you want.
And access your response status in your ajax success handler like below
$.ajax({
//...
success: function(data, textStatus, xhr) {
console.log(xhr.status);
}
});

Jquery post callback function fail and done always being called

I have an API controller that returns a HttpStatusCodeResult 200 if it worked and 500 if they weren't able to register. The problem is .done and .fail will both be called no matter what status code is returned. However the information is posted or not posted correctly. Here is my post function. Any ideas what could be causing this would be greatly appreciated?
function register() {
$.post("../api/Register",
{
'Email': $("#rEmail").val(),
'Password': $("#rPassword").val()
})
.done((function () {
alert("Thank you for registering!");
})())
.fail((function () {
alert("Email already exists");
})());
}
Edit: The problem is that it was reloading the page when jquery.unobtrusive is supposed to prevent that from happening. The fix or workaround was changing it to a button and not a form.
Instead of passing the anonymous functions you were invoking it as a IIFE by adding () at the end of the function
function register() {
$.post("../api/Register", {
'Email': $("#rEmail").val(),
'Password': $("#rPassword").val()
}).done(function () {
alert("Thank you for registering!");
}).fail(function () {
alert("Email already exists");
});
}
The problem is you're immediately executing the functions that are getting passed to done and fail. That's causing these functions to be executed right then and there.
So just pass the function itself by changing this
.done((function () {
alert("Thank you for registering!");
})())
to this
.done(function () {
alert("Thank you for registering!");
})
You really shouldn't be sending an http status of 500 on an expected registration failure such as "email already exists" condition... this should be handled by a parameter that denotes success / failure as part of a 200 response.
You can handle unexpected internal server errors (status 500) using success or error callbacks like so:
$.ajax({
url : "../api/Register",
type : "post",
data : {"Email" : "you#example.com", "Password" : "pw"},
dataType : "json",
success : function(response){
// handle http 200 responses
if(response.registrationApproved){
alert("Thank you for registering!");
}else{
alert("email exists");
}
},
error : function(){
// handle 500 or 404 responses
alert("server call failed");
},
complete : function(){
// if needed.. this will be called on both success and error http responses
}
});

add global callback to $.ajaxSetup

I am use $.ajaxSetup to use a global authorization method, and global error handling in my site. I would like to pass a callback function into the global error method so I can call the function whenever I need to in the global error handler. Here is my $.ajaxSetup:
$.ajaxSetup({
global: false,
// type: "POST",
beforeSend: function (xhr) {
//The string needs to be turned into 'this.pasToken'
//if not us, don't include
if(app.cookieAuth)
xhr.setRequestHeader("Authorization", _this.pasToken);
},
statusCode: {
401: function(){
//Redirect to the login window if the user is unauthorized
window.location.href = app.loginUrl;
},
//This is where I need help
403: function(error, callback){
//Show an error message if permission isn't granted
callback(error);
alert(JSON.parse(error.responseText)['Message']);
}
}
});
Note the 403: status code. I am trying to pass in a callback function, but I don't know how to do it from the individual ajax calls. Anyone have an idea?
The easiest solution; define your own property for ajax options.
$.ajaxSetup({
statusCode: {
403: function(error, callback){
this.callback403(error);
}
}
});
$.ajax({
callback403: function () {}
});
Note, if you change the context option of the ajax request, this may not work.
I am not sure if this is what you are looking for:
$.ajax({
statusCode: {
404: function() {
alert("page not found");
}
}
});

Javascript: How to stop multiple jQuery ajax error handlers?

A team member put this into our project
$(function() {
$("body").bind("ajaxError", function(event, XMLHttpRequest, ajaxOptions, thrownError){
alert(thrownError);
});
}
However I want to supress one of my errors (as it would be noise and verification isn't needed)
function blah() {
...
errFunc = function(event, xhr, opts, errThrown) {
//what could I do here?
//event.stopImmediatePropagation()?
}
$.ajax({
url : '/unimportant_background_refresh',
type : 'GET',
data : { },
dataType : 'json',
success : updateBackgroundStuff,
error : errFunc, // Suppresses error message.
});
}
How can I stop the catch all error from happenning please? Can I just do something in the error function such as { event.StopPropogation(); } or must I work out some mechanism for having the catch all selectively ignore things please?
Global events can be disabled, for a particular Ajax request, by passing in the global option, like so:
$.ajax({
url: "test.html",
global: false,
// ...
});
Taken from: http://docs.jquery.com/Ajax_Events
I would just throw a boolean into your code that's defaulted to false. Set it to true the first time the error is thrown and make sure to check for true at the start of the error function.
Something like:
function blah() {
var errorHappened = false;
...
errFunc = function(event, xhr, opts, errThrown) {
if (errorHappened)
return;
errorHappened = true;
// handle the errror.
}
// the rest of your code
}

Can I evaluate the response type of an $.ajax() call in success callback?

I am using jQuery to make an AJAX request to a remote endpoint. That endpoint will return a JSON object if there is a failure and that object will describe the failure. If the request is successful it will return HTML or XML.
I see how to define the expected request type in jQuery as part of the $.ajax() call. Is there a way to detect the request type in the success handler?
$.ajax(
{
type: "DELETE",
url: "/SomeEndpoint",
//dataType: "html",
data:
{
"Param2": param0val,
"Param1": param1val
},
success: function(data) {
//data could be JSON or XML/HTML
},
error: function(res, textStatus, errorThrown) {
alert('failed... :(');
}
}
);
Have you application generate correct Content-Type headers (application/json, text/xml, etc) and handle those in your success callback. Maybe something like this will work?
xhr = $.ajax(
{
//SNIP
success: function(data) {
var ct = xhr.getResponseHeader('Content-Type');
if (ct == 'application/json') {
//deserialize as JSON and continue
} else if (ct == 'text/xml') {
//deserialize as XML and continue
}
},
//SNIP
);
Untested, but it's worth a shot.
how about using the complete option?
$.ajax({
...
complete : function(xhr, status) {
// status is either "success" or "error"
// complete is fired after success or error functions
// xhr is the xhr object itself
var header = xhr.getResponseHeader('Content-Type');
},
...
});
By the time it calls your success handler, the data has already been deserialized for you. You need to always return the same data type for any successful result. If there truly is an error, you should probably throw an exception and let it get handled by the error callback instead. This should be able to parse the resulting error and package it for your callback, that is, it will detect that the response did not have 200 OK status and parse the result to obtain the error information.

Categories