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

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.

Related

jQuery.Ajax Error result

Im using MVC on server side and calling a function via jQuery.Ajax sending json type.
the function results with exception.
i want to invoke/trigger the error result function of the Ajax, what should i send back with the return JSON function?
for the example, let's say the return JSON is triggered from the catch section.
MVC Function
public JsonResult Func()
{
try
{
var a = 0;
return Json(a, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
FxException.CatchAndDump(ex);
return Json(" ", JsonRequestBehavior.AllowGet);
}
}
JavasScript call
$.ajax({
url: '../Func',
type: 'GET',
traditional: true,
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
alert('s');
},
error: function (data) {
alert('e');
}
});
Quoting from this answer:
The error callback will be executed when the response from the server is not going to be what you were expecting. So for example in this situations it:
HTTP 404/500 or any other HTTP error message has been received
data of incorrect type was received (i.e. you have expected JSON, you have received something else).
The error callback will be executed when the response from the server is not going to be what you were expecting. So for example in this situations it:
HTTP 404/500 or any other HTTP error message has been received
data of incorrect type was received (i.e. you have expected JSON, you have received something else).
In your situation the data is correct (it's a JSON message). If you want to manually trigger the error callback based on the value of the received data you can do so quite simple. Just change the anonymous callback for error to named function.
function handleError(xhr, status, error){
//Handle failure here
}
$.ajax({
url: url,
type: 'GET',
async: true,
dataType: 'json',
data: data,
success: function(data) {
if (whatever) {
handleError(xhr, status, ''); // manually trigger callback
}
//Handle server response here
},
error: handleError
});
error callback is invoked when HTTP response code is not 200 (success) as well as when response content is not comply to expected contentType which is json in your case.
So you have to either send HTTP header with some failure response code (e.g. 404) or output non-json response content. In the latter case you can simply output empty string:
return "";
If you want to trigger an error in AJAX, but still know "why" it was triggered so you can customize the error message, see this post:
https://stackoverflow.com/a/55201895/3622569

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

JSON data not responding

Following is my code :
function jsonpCallback(response){
//JSON.stringify(response)
alert(response);
}
$.ajax({
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) {
alert(error);
},
success: function(data) {
alert(data);
jsonpCallback(data);
}
});
Here my url variable is the link which contain the following data and as per I know it is in the JSON format:
[{"destination":"United States","destinationId":"46EA10FA8E00","city":"LosAngeles","state":"California","country":"United States"}] etc..
I want to call jsonpCallback function after passing successive data to it. But success argument of $.ajax is not calling the function thats why I am not getting any data into it. But my debugger window showing response there, so why its not coming $.ajax function?
Any help...thanks in advance.
Try to pass type of ajax call GET/POST.
$.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) { alert(error); },
success: function(data) {
alert(data);
jsonpCallback(data);
}
});
function jsonpCallback(response){
//JSON.stringify(response)
alert(response);
}
The URL you are trying to load data from doesn't support JSONP, which is why the callback isn't being called.
If you own the endpoint, make sure you handle the callback GET parameter. In PHP, your output would look like this:
<?php
echo $_GET['callback'].'('.json_encode($x).')';
This will transform the result to look like this:
jsonp2891037589102([{"destination":"United States","destinationId":"46EA10FA8E00","city":"LosAngeles","state":"California","country":"United States"}])
Of course the callback name will change depending on what jQuery generates automatically.
This is required as JSONP works by creating a new <script> tag in the <head> to force the browser to load the data. If the callback GET parameter isn't handled (and the URL returns a JSON response instead of a JSONP response), the data gets loaded yes, but isn't assigned to anything nor transferred (via a callback) to anything. Essentially, the data gets lost.
Without modifying the endpoint, you will not be able to load the data from that URL.
One weird thing I've noticed about $.ajax is that if the content-type doesn't match exactly it's not considered a success. Try playing around with that. If you change success to complete (and fix the arguments) does it alert?
It's not working because your server does not render a JSONP response. It renders a JSON response.
For JSONP to work, the server must call a javascript function sent by the ajax request. The function is generated by jQuery so you don't have to worry about it.
The server has to worry about it, though. By default, this function's name is passed in the callback argument. For example, the URL to the server will be http://some.domain/ajax.php?callback=functionName (notice callback=functionName).
So you need to implement something like the following on the server side (here in PHP):
$callback = $_GET['callback'];
// Process the datas, bla bla bla
// And display the function that will be called
echo $callback, '(', $datas, ');';
The page returned will be executed in javascript, so the function will be called, so jQuery will call the success function.
First check in which event you are calling $.ajax function...
<script type='text/javascript'>
jQuery('#EnrollmentRoleId').change(function(){
alert("ajax is fired");
$.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) { alert(error); },
success: function(data) {
alert(data);
jsonpCallback(data);
}
});
});
function jsonpCallback(response){
//JSON.stringify(response)
alert(response);
}
</script>
second try to replace $ with jQuery.
Try to give no conflict if you thinking any conflict error..
jQuery ajax error callback not firing
function doJsonp()
{
alert("come to ajax");
$.ajax({
url: url,
dataType: "jsonp",
crossDomain: true,
jsonpCallback:'blah',
success: function() { console.log("success"); },
error: function() { console.log("error"); }
});
}
Then check your json data if it is coming it is valid or not..
Thanks

Check for 404 error status in jquery

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(){
}
}
});

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.

Categories