Check for 404 error status in jquery - javascript

I use this code to get some information from twitter via their api:
$.ajax({
url : apiUrl,
cache : false,
crossDomain: true,
dataType: "jsonp",
success : function(html) {
// ...
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
}
});
However, if the apiUrl variable provides a correct url, this code work fine, e.i. the success object is executed, but if the url isn't correct, e.i. 404 error is returned from twitter, the error object is never executed. It doesn't log anything in console. How should I check for 404 error status in this case?

From jQuery API ajax docs:
error option
Note: This handler is not called for cross-domain script and JSONP
requests.
http://api.jquery.com/jQuery.ajax/

According to the docs, use statusCode setting in .ajax.
$.ajax({
...
statusCode: {
404: function(){
}
}
});

Related

jQuery Ajax get fail message like Chrome console

I'm going to go crazy.
When I i jQuery Ajax function to a request, I get in console this error
OPTIONS [myURL] net::ERR_NAME_NOT_RESOLVED
It is possible to get the error text net::ERR_NAME_NOT_RESOLVED in my JavaScript?
I read all documentation about jQuery Ajax but I can't understand where I can find this message.
Thanks a lot.
This is the simplified Ajax call. The URL is simply a variable of a WebService.
$.ajax({
method: "GET",
url: myURL,
dataType: "json",
})
.done(function(response) {
console.log(response)
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.error("------AJAX error");
});

$.post not triggering function

I really don't get why alert or console.log is not being triggered in this code:
$.post("http://localhost:8080/mail",
jsonObject,
function(data) {
console.log("Done!");
alert("Thank you for your inquiry. We will get back to you soon.");
alert("Response: " + JSON.stringify(data));
}
);
While I can see the mail API works as I was able to get the email with the values I put in the HTML forms. alert and console.log is not being triggered what could be the reason?
I can see this on the browser log though:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://localhost:8080/mail. This can be fixed
by moving the resource to the same domain or enabling CORS.
Could this be the reason? If so what should I do to make $.post trigger success or failure.
Cross Origin Requests (CORS) is your issue. $.ajax() crossDomain parameter as documented here
If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain.
$.ajax({
type: "POST",
url: "http://localhost:8080/mail",
crossDomain : true,
data: jsonObject
...
})
Regarding how to catch a success or failure: You can chain done(), fail(), and always() to $.post
$.post("http://localhost:8080/mail", jsonObject, function(data) {
// alert("success");
}).done(function(){
// alert("success 2");
}).fail(function() {
// alert( "error" );
}).always(function(){
// alert( "finished" );
});
Which also works with $.ajax() or use callbacks within $.ajax()
$.ajax(function(){
success: function (responseData, textStatus, jqXHR) {},
error: function (responseData, textStatus, errorThrown) {}
});

jquery ajax does not complete

I'm having a trouble with ajax requests and server responses:
$.ajax({
url: servurl,
dataType: "jsonp",
data: {... },
crossDomain: true,
error: function(){},
success: function(){},
complete: function(){alert('complete')}
});
}
The thing is - sometimes I get succes, when I should get it, but sometimes I can get 500 status, and it is normal and expected.
The same ajax call works for correct requests, but fails for others.
I want to display an error message if I get a 500 server error, but for some reason the ajax does not complete. Thus, neither error: nor complete: work.
Maybe the reason for that is 'jsonp' datatype? Other datatypes do not work though.
Can someone help please?
Or maybe give me an advice on how to detect server status any other way.
jsonp requests do not trigger error callbacks by design, therefore there is no way for you to catch the error with javascript. I suggest instead implementing an error handler on your server that detects a jsonp request and returns jsonp that indicates an error has occured rather than a 500 status code.
Note that error: is deprecated as of 1.8 and is not called for JSONP however I wonder if you might have success using the Promise functionality introduced with 1.5 for deferred http://api.jquery.com/category/deferred-object/ as:
jqXHR.fail(function(jqXHR, textStatus, errorThrown) {});
jqXHR.done(function(data, textStatus, jqXHR) {});
jqXHR.always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { });
Example for your code:
$.ajax({
url: servurl,
dataType: "jsonp",
data: {... },
crossDomain: true
}).done(function(data, textStatus, jqXHR){ //replace success
alert(textStatus);
}).always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { // replace complete
alert(textStatus);
}).fail(function(jqXHR, textStatus, errorThrown) { // replace error
alert(errorThrown);
});
Make sure that you are accessing to your server. Maybe you are requesting in your server for an specific contentType (like application/json) and you are not using that property into your ajax call.
As you requested, to show any message if get a error (400, 404, 500...), you can use my custom function for ajax error responses:
function onErrorFunc(jqXHR, status, errorText) {
alert('Status code: ' + jqXHR.status + '\nStatus text: ' + status +
'\nError thrown: ' + errorText);
}
Usage:
$.ajax({
//some options
error: onErrorFunc
});
Please, show us what error thrown your server.
Thank you all for comments. Jquery .ajax really does not give errors on jsonp requests.
The way to get error messages was to implement the jquery-jsonp plugin:
https://github.com/jaubourg/jquery-jsonp

jQuery Ajax - how to get response data in error

I have a simple web application.
I've created the server REST API so it will return a response with HTTP code and a JSON (or XML) object with more details: application code (specific to scenario, message that describe what happened etc.).
So, for example if a client send a Register request and the password is too short, the response HTTP code will be 400 (Bad Request), and the response data will be: {appCode : 1020 , message : "Password is too short"}.
In jQuery I'm using the "ajax" function to create a POST request. When the server returns something different from HTTP code 200 (OK), jQuery defines it as "error".
The error handler can get 3 parameters: jqXHR, textStatus, errorThrown.
Ho can I get the JSON object that sent by the server in error case?
Edit:
1) Here is my JS code:
function register (userName, password) {
var postData = {};
postData["userName"] = userName;
postData["password"] = password;
$.ajax ({
dataType: "json",
type: "POST",
url: "<server>/rest/register",
data: postData,
success: function(data) {
showResultSucceed(data);
hideWaitingDone();
},
error: function (jqXHR, textStatus, errorThrown) {
showResultFailed(jqXHR.responseText);
hideWaitingFail();
}
})
}
2) When looking at Firebug console, it seems like the response is empty.
When invoking the same request by using REST testing tool, I get a response with JSON object it it.
What am I doing wrong?
Here's an example of how you get JSON data on error:
$.ajax({
url: '/path/to/script.php',
data: {'my':'data'},
type: 'POST'
}).fail(function($xhr) {
var data = $xhr.responseJSON;
console.log(data);
});
From the docs:
If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object.
Otherwise, if responseJSON is not available, you can try $.parseJSON($xhr.responseText).
directly from the docs
The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of
jQuery 1.5 is a superset of the browser's native XMLHttpRequest
object. For example, it contains responseText and responseXML
properties, as well as a getResponseHeader()
so use the jqXRH argument and get the responseText property off it.
In the link above, look for the section entitled
The jqXHR Object
I also faced same problem when i was using multipart/form-data. At first I thought multipart/form-data created this mess, but later i found the proper solution.
1) JS code before:
var jersey_url = "http://localhost:8098/final/rest/addItem/upload";
var ans = $.ajax({
type: 'POST',
enctype: 'multipart/form-data',
url: jersey_url,
data: formData,
dataType: "json",
processData: false,
contentType: false
success : funtion(data){
var temp = JSON.parse(data);
console.log("SUCCESS : ", temp.message);
}
error : funtion($xhr,textStatus,errorThrown){
console.log("ERROR : ", errorThrown);
console.log("ERROR : ", $xhr);
console.log("ERROR : ", textStatus);
}
});
Here when error occurred, it showed me this in console :-
Error :
Error : { abort : f(e), always : f(), .... , responseJSON :"{"message":"failed"}" }
Error : error
Thus i came to know that we have to use $xhr.responseJSON to get the string message which we sent from rest api.
2) modified/working error funtion:
error : funtion($xhr,textStatus,errorThrown){
var string= $xhr.responseJSON;
var json_object= JSON.parse(string);
console.log("ERROR : ", json_object.message);
}
Thus will output "Error : failed" on console.
After spending so much time on this problem, I found the problem.
The page is under the URL: www.mydomain.com/register
The REST api is under the URL: server.mydomain.com/rest
Seems like this kind of POST is not so simple.
I'm going to search more information to understand this issue better (if you have more information please share it with me).
When putting the REST API under www.mydomain.com/rest - everything is working fine.

How to handle ajax errors that were not handled by statusCode?

I am making the following ajax call:
$.ajax({
type: type,
url: url,
data: data,
success: successCallback,
error: defaultFailureCallback,
dataType: 'json',
statusCode: statusCode
});
I am passing a few HTTP status codes in the statusCode parameter and the corresponding errors are handled by the respective functions. Now I want the defaultFailureCallback function to handle all the other error codes. How do I do this?
The signature of the error function in jQuery is: error(jqXHR, textStatus, errorThrown)
The problem I am facing is that there is no way to access the actual statusCode parameter inside the defaultFailureCallback function. jqXHR does not seem to contain that information. (I can get the current status from jqXHR.status)
jqXHR should have the property status, see: http://api.jquery.com/jQuery.ajax/#jqXHR
The solution is to use this variable which will contain the statusCode values too.

Categories