Error handling cross domain jquery ajax call - javascript

I am performing one cross domain get operation as shown below.
$.ajax({
type: "GET",
url: "http://localhost:65249/api/item/get",
data: {
searchText: "test"
},
dataType: "jsonp",
async: false,
success: function (results) {
alert(results);
},
error: function (jqXHR, error, errorThrown) {
if (jqXHR.status && jqXHR.status == 401) {
alert("Unauthorized request");
} else if (jqXHR.status && jqXHR.status == 404) {
alert("The requested page not found");
}
}
});
But success or error block is not getting called after request is completed. when i debug java script in developer console i am receiving error but error block of javascript is not getting called.
GET http://localhost:65249/api/item/getallproducts?callback=jQuery182028460139059461653_1396510235829&searchText=test&_=1396510674779 401 (Unauthorized)

Unfortunately, if you are using JSONP, all requests that return an error fail silently. This is because JSONP uses a script tag instead of XmlHttpRequest. If you want errors to fire, you need to use XHR with CORS. CORS needs to be configured on the server side, and it works client side only in IE 10+.

error dont work on corss domain calls, see jquery doku. for error:
Note: This handler is not called for cross-domain script and
cross-domain JSONP requests.
Take a look at this answer:
JSONP request error handling

Related

javascript Cross-Origin Read Blocking (CORB) blocked cross-origin response

I am trying to retrieve JSON responses from an API. I keep getting "Cross-Origin Read Blocking (CORB) blocked cross-origin response", causing an error. I have searched the web trying to find what could be the issue but I am failing.
The API has to return a generated session.
When I inspect the header I see that there are multiple headers attached to the request.
The funny thing is that when i copy the URL directly on to my web browser, i get the json response with the values but once i use the url in an ajax function, i get denied.
jQuery.ajax({
type: 'GET',
crossOrigin: true,
url: "https://apitest.mobzgo.co.za/getSession?username=********&passingword=*****",
dataType: "jsonp",
contentType: "jsonp;",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (jqXHR, exception, errorThrown) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status === 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status === 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = errorThrown;
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
alert(msg);
}
});
CORB errors occur when you try to treat some data from a different origin as if it was a different kind of data.
e.g. <img src="http://example.com/foo.html"> - an HTML document is not an image.
In this case you said dataType: "jsonp", so you are trying to treat the URL as JavaScript (since JSONP is specially formatted JavaScript). It isn't JavaScript so, rather then trying to execute it and throwing an exception from that, it just throws an exception when it detects it isn't JS.
Aside: contentType: "jsonp;", — JSONP isn't a content-type and you are making a GET request so there is no request body to describe the type of anyway. What's more, JSONP requests can't set the content-type. This is wrong and pointless in multiple ways.
Note also that JSONP is nasty. It is limited and has security concerns. When building an API today there is no good reason to support cross-origin requests using JSONP. We have CORS now. CORS is much safer and more powerful.

jQuery jsonp catch "Failed to load resources…"

I have a Javascript function where I get data via JSONP from my server. I have tried to simulate server errors or lack of internet access (it is supposed to run in a cordova app, so it's possible the client doesn't have internet access), but I can't catch the error. Here is my code:
var completed = false;
jQuery.ajax({
url: "http://www.someDomainThatDoesn'tWork.com/getsContent.php?callback=?",
dataType: "json",
success: function(data) {
completed = true
console.log(data);
},
error: function() {
console.log("fail");
},
statusCode: {
404: function() {
console.log("fail 2");
}
}
}).fail(function() {
console.log("fail 3");
}).always(function() {
if (!completed) {
console.log("fail 4");
}
});
As you can see I try to catch (different) errors in four places. However, if I for example edit the url to one that doesn't exist, the javascript just aborts and give me the error
Failed to load resource: the server responded with a status of 404 (Not Found)
and none of the error catchers gets executed.
In the documentation for jQuery.ajax() it says
Note: This handler is not called for cross-domain script and cross-domain JSONP requests.
so I guess I shouldn't be surprised.
Is there any way to catch this error? I have also tried to embrace it with
try{} catch(error) {}
but that doesn't do the trick either.
Because the JSONP method returns a script it likely fails silently, you may need to change your server to use CORS and not use JSONP in order to be able to get proper error handling.

Jquery Ajax call return 403 status

I have a jquery Ajax call implemented for keepalive the session, this keepAlive() method will call in every 20 mins
function keepAlive() {
$.ajax({ type: "POST",
url: "KeepAliveDummy.aspx", cache: false
});
}
This call is happen when the third party contents are loaded in to the frameset,
I'm getting 403 http status (check via fiddler) on this request,
Will this impact the end result of refresh the session time out?
Since your question is about handling 403 error (Will this impact the end result of refresh the session time out?) rather what 403 is.
So, handle this error, you can log or notify.
$.ajax({
type: "POST",
url: "KeepAliveDummy.aspx",
success: function (response) {
//session refreshed
},
error: function (xhr, ajaxOptions, thrownError) {
if(xhr.status==403) {
//handle error
}
}
});
about 403 :
403 Forbidden The request was a valid request, but the server is
refusing to respond to it.[2] Unlike a 401 Unauthorized response,
authenticating will make no difference.[2]
it needs you to authenticate (like login) first before do call ajax. 401 error requires authenticating header field when request but 403 doesn't.
check your server or contact who has responsibility for authentication.

IE is not handleing 401 error

I have an ajax call that is partly used to check to see if you are logged in.
function userInfo(){
return $.ajax({
url: "http://api.itassistteam.com/api/account/isloggedon",
type: "GET",
dataType: "json",
xhrFields: {
withCredentials: true
},
statusCode: {
401: function(){
console.log("401 error.");
deleteCookie();
window.location.href = "./login.html";
}
},
});
}
In Chrome, FF and Opera, it redirects to the log in page like it's supposed to, but in IE it does nothing. When I look in the console, it says
SCRIPT7002: XMLHttpRequest: Network Error 0x80070005, Access is denied.
Any idea why IE will not take the error handler and redirect to login? The "401 error." message does not appear in the console.
Instead of statusCode I used error. This is how you get the same results with error that you would get with
statusCode : {
401: function(){...}
}
You do,
error: function(jqXHR, textStatus, errorThrown){
if(jqXHR.status == 401){
...
}
}
This is consistent across all major browsers unlike the statusCode method witch doesn't work with IE. This way you can have error handling specific to the error in IE.

jQuery ajax - Absolute URL's and error handling

Is it possible to catch the HTTP errors (like 404, 500, 504 etc) when we call an external webservice by specifying an absolute url?. (like setting the url: attribute of $.ajax call to have a url value as http://api.geonames.org/findNearbyPostalCodes.
Right now I'm unable to receive any errors although firebug is catching them and showing it in the console.
Can someone help?
Here is my code.
$.ajax({
type: 'GET',
url: "http://api.geonames.org/findNearbyPostalCodes",
data: '{"lat":47,"lng":"9","username":"demo"}',
dataType: 'json',
cache:false,
async:false,
statusCode:{
404: function(){
alert('Page not found');
},
500: function(){
alert('Page not found');
},
504: function(){
alert('Unknown host');
}
},
success: function(data){
alert(data);
}
error: function (xhr, exception, thrownError)
{
alert(xhr.status);
}
});
No, it is not possible with cross-domain (external) requests using only client-side code. This is because cross-domain requests rely on JSONP - ie, injecting a script tag that loads code from an external source. Unfortunately, the <script> element does not have anything like an onerror event.
You can handle errors with same-domain requests because these typically use XMLHttpRequest, which returns a lot of useful information like status codes and response headers.
Your best bet would be to use your local server as a proxy.
If using an absolute URL causes the domain to be different from the domain of your page (cross-domain request), then the only way to successfully execute an ajax call is to use JSONP which will cause the ajax library to use <script> tags for the cross-domain request instead of the more typical XMLHttpRequest used for same-domain requests.
You will not be able to intercept any sort of status codes from the loading of the cross-domain <script> tag.
In your case, you cannot check the status code (assuming you're not making the request from api.geonames.org).
jQuery will always return a "0" as the status if the request is cross-domain:
$.ajax({
type: 'GET',
url: 'http://someotherdomain.com/api/query',
dataType: 'json',
data: '{"first": 1, "second": 2}',
complete: function(response) { // the 'response' object has the status code
if (response.status == '200') {
// do something on success
} else if (response.status == '0') {
alert('Your request is cross-domain');
}
}
});
If the request happens to be within the same domain, you'll get a valid status code that you can check (the complete attribute of the $.ajax() function will run after any success or failure callbacks are run).

Categories

Resources