Json Response is undefined - javascript

This is driving me nuts, I have been through every article I have seen on Google and here and two days later, 101 variants later I am still no further forward.
The success 201 works perfectly, I get an alert with bound items. The 404 doesn't work at all, no matter what I try the ErrorDesc is always undefined. I have got it working that it can hit this 404 function with a fixed string, but I want the user to know why there is an error.
I have used fiddler to look at the request and response. It looks fine, both the request and response are well formed JSON:
Raw Request:
{"Bedrooms":"3","BuildingsAD":"Yes","BuildingsMD":"No","BulidingSI":"100000","ContentsAD":"No","ContentsMD":"No","ContentsPOL":"No","ContentsSI":"5000","EffectiveDate":"03/10/2012 23:40:10","EL":"N","MD":"No","NCD":"1","POL":"No","PropType":"Terraced","RiskPostcode":"SW19 1TS","SchemeRef":"20","TA":"No","TenantTheft":"No","TenantType":"Professional","Theft":"No","TransactionDate":"03/10/2012 23:40:10","VolExcess":"250","YearBuilt":"2000 +","ErrorDesc":"123"}
Raw Response:
{"RatingId":"f5733e9d-bc9d-4026-8d5f-ce4f750a3a42","SchemeRef":"20","EffectiveDate":"03/10/2012 23:40:10","TransactionDate":"03/10/2012 23:40:10","Bedrooms":"3","BuildingsAD":"Yes","BuildingsMD":"No","BulidingSI":"100000","ContentsAD":"No","ContentsMD":"No","ContentsPOL":"No","ContentsSI":"5000","EL":"N","MD":"No","NCD":"1","POL":"No","PropType":"Terraced","RiskPostcode":"SW19 1TS","TA":"No","TenantTheft":"No","TenantType":"Professional","Theft":"No","VolExcess":"250","YearBuilt":"2000 +","Error":true,"ErrorDesc":"Rating Sheet not found"}
<script type="text/javascript">
function CalcRating() {
//create a Json object based on data entered by user
var RatingItems = {
AD: $("#AD").val(),
AdminFee: $("#AdminFee").val(),
Bedrooms: $("#Bedrooms").val(),
BuildingsAD: $("#BuildingsAD").val(),
BuildingsMD: $("#BuildingsMD").val(),
BuildingsPremium: $("#BuildingsPremium").val(),
BulidingSI: $("#BulidingSI").val(),
ContentsAD: $("#ContentsAD").val(),
ContentsMD: $("#ContentsMD").val(),
ContentsPOL: $("#ContentsPOL").val(),
ContentsPremium: $("#ContentsPremium").val(),
ContentsSI: $("#ContentsSI").val(),
EffectiveDate: $("#EffectiveDate").val(),
EL: $("#EL").val(),
IPT: $("#IPT").val(),
MD: $("#MD").val(),
NCD: $("#NCD").val(),
POL: $("#POL").val(),
PropType: $("#PropType").val(),
RatingId: $("#RatingId").val(),
RiskPostcode: $("#RiskPostcode").val(),
SchemeRef: $("#SchemeRef").val(),
TA: $("#TA").val(),
TenantTheft: $("#TenantTheft").val(),
TenantType: $("#TenantType").val(),
Theft: $("#Theft").val(),
TransactionDate: $("#TransactionDate").val(),
TotalPremium: $("#TotalPremium").val(),
VolExcess: $("#VolExcess").val(),
YearBuilt: $("#YearBuilt").val(),
ErrorDesc: "123"
};
//call jQuery Ajax method which calls Json.stringify method to convert
//the Json object into string and send it with post method
$.ajax({
url: "/api/qsletpropertyom",
data: JSON.stringify(RatingItems),
type: "POST",
contentType: "application/json;charset=utf-8",
statusCode: {
201: function (result) {
alert("Total Premium: " + result.TotalPremium + ", Total Buildings Premium " + result.BuildingsPremium + ", Total Contents Cover " + result.ContentsPremium + ", Admin Fee " + result.AdminFee);
},
404: function (result1) {
alert(result.ErrorDesc);
},
500: function (result2) {
alert("Unknown Error");
}
}
});
}
Please let me know the error of my ways!!

First of all, you're using result.ErrorDesc when you were probably expecting result1.ErrorDesc - but that's just a typo I guess.
Second of all, if I get you right, you want to display error description to the user when ajax hits 404 (page not found)? If so, most likely you won't be able to do that since there is no data passed to your 404 handler.
Perhaps you're looking for something else like error option for ajax (http://api.jquery.com/jQuery.ajax/).
From jQuery documentation: error "A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests."
$.ajax({
url: "/api/qsletpropertyom",
data: JSON.stringify(RatingItems),
type: "POST",
contentType: "application/json;charset=utf-8",
error: function(jqXHR, textStatus, errorThrown) {
// textStatus will contain "Not Found" for 404 errors
}
});
EDIT:
Apparently, the 404 handler used in statusCode map definition (as you did) gets 3 arguments, just as error option does. Here's working example: http://jsfiddle.net/QsHdV/2/
Note that first argument you get there is jquery XHR object not some result data.

I think the issue is that you are expecting to get the response text as the first argument in the 404 case, which is not what jQuery returns.
Here some info taken from the jQuery docs :
statusCode(added 1.5)Map
If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error, they take the same parameters as the error callback.
error(jqXHR, textStatus, errorThrown) Function
A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests. This is an Ajax Event.
success(data, textStatus, jqXHR)Function, Array
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
As you can see, you aren't given a response data object as an argument when an HTTP error occurs.

Related

What are "succes" and "error" in a jQuery ajax call?

I am writing papper about JavaScript and if url, method and data are arguments that method recives then what about success and error? are they arguments or are they called something else?
$.ajax({
url: "url",
method: "get",
data: {
"someData":someData
},
success: function (data) {
alert(data);
},
error: function (errorThrown) {
alert(errorThrown);
}
});
Both success and error are callback functions,
In short success and error are to specify what to do in case
of success or failure of the request respectively.
From Jquery API
success
Type: Function( Anything data, String textStatus, jqXHR jqXHR ) A
function to be called if the request succeeds. The function gets
passed three arguments: The data returned from the server, formatted
according to the dataType parameter or the dataFilter callback
function, if specified; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the
success setting can accept an array of functions.
error
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown ) A
function to be called if the request fails. The function receives
three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a
string describing the type of error that occurred and an optional
exception object, if one occurred. Possible values for the second
argument (besides null) are "timeout", "error", "abort", and
"parsererror". When an HTTP error occurs, errorThrown receives the
textual portion of the HTTP status, such as "Not Found" or "Internal
Server Error." As of jQuery 1.5, the error setting can accept an array
of functions. Each function will be called in turn.
So how it works ?
AJAX communicates with the server using XMLHttpRequest object
User sends a request from the UI and a javascript call goes to XMLHttpRequest object.
HTTP Request is sent to the server by XMLHttpRequest object.
Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.
Data is retrieved.
Server sends XML data or JSON data to the XMLHttpRequest callback function.
A success callback that gets invoked upon successful completion of an Ajax request
A failure callback that gets invoked in case there is any error while making the request
HTML and CSS data is displayed on the browser.
They are also arguments, but could also be called callback functions
They are callback functions.
When ajax call , in your case get call, successfully completed then success() function will be called and particular functionality inside will be get executed and if any error is there then error() function will be called and get executed
When you make a backend call after the page is loaded in browser its known as AJAX (Asynchronous Javascript). This method will fetch the data from the server without reloading the page.
Now as you are making a server call, you will be facing two scenarios
Success = your call is successful and server is giving you the requested data.
Error = your call has failed due to two major reasons
2a. Either your url is wrong or the url you specified is not defined to match the backend server. In this case, you get 404 error
2b. Your url is correct, but you are not passing the right parameters for the server to respond or you are passing some data which is not required by that url
For example, for a login verification you need to pass username and password. Instead if you pass as email and password, it will throw error.
$.ajax takes an argument of options, which is a generic object. success and error are callback functions that are members of the options object. So, you could call them many things. I would refer to them as callback functions.
success and error are callback handlers.success() is the success
handler which is called when the server returns a valid response
(200 status code) and error() is the error handler which is
called when the server fails to respond to a valid request(500
response code)

calling Web service via ajax - proper response in my error callback

I am trying to get some data from a web service via ajax using the below function,
but I get this response message:
{"readyState":4, "status":200, "statusText":"load"}
The WS is supposed to return an array of json and, if I look in my chrome dev tool
in network tab -> Response, I actually get the proper array of json.
Question:
Why am I getting the result in my errorFunction callback?
function callWebService(wsUrl, params, successFunction, errorFunction) {
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader('Access-Control-Allow-Methods', ' GET');
xhr.setRequestHeader("Content-Type",
"application/json; charset=utf-8");
xhr.setRequestHeader("Accept", "application/json");
},
type: "GET",
url: wsUrl,
data: params,
dataType: "json",
contentType: "application/json",
success: successFunction,
error: errorFunction
});
}
Here is my console.log when I use this error function function(jqXHR, status, error)
*Resource interpreted as Script but transferred with MIME type text/html: "http://www.myweb.it/services/service.php?callback=jQu…y21109160579217132181_1405523828314&codice_istituto=150201&_=1405523828315". jquery.js:8691send jquery.js:8691jQuery.extend.ajax jquery.js:8152callWebService global.js:5(anonymous function) index.js:49jQuery.event.dispatch jquery.js:4409elemData.handle jquery.js:4095
an error occurred: index.js:52
parsererror index.js:53
Error {stack: (...), message: "jQuery21109160579217132181_1405523828314 was not called"}message: "jQuery21109160579217132181_1405523828314 was not called"stack: (...)get stack: function () { [native code] }set stack: function () { [native code] }__proto__: d index.js:54
readyState: 4 index.js:56
jqXHR.status: 200 index.js:57
jqXHR.statusText:load index.js:58
jqXHR.responseText: undefined*
You're seeing the error callback fired because there's something wrong with your AJAX request, and it's not returning successfully. Identifying why this happens is another matter.
The first argument jQuery passes to your error callback is the jqXHR object:
error
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )
This is different from the success callback, which begins with the data returned:
success
Type: Function( PlainObject data, String textStatus, jqXHR jqXHR )
jqXHR is a superset of the xmlHttpRequest object JavaScript returns. Inside it, you're seeing readyState of 4, which simply means "done", and status of 200 means a successful request. So, at least you know you're probably pointing your request at the right URL.
You should be able to get other information from your jqXHR object which might help you identify the cause of the error. From the docs:
For backward compatibility with XMLHttpRequest, a jqXHR object will
expose the following properties and methods:
readyState
status
statusText
responseXML and/or responseText when the underlying request responded with xml and/or text, respectively
setRequestHeader(name, value) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
getAllResponseHeaders()
getResponseHeader()
statusCode()
abort()
That object you're seeing is an XMLHTTPResponse; a representation of the actual AJAX request. You're getting it passed into your error handler because that's the first argument of jQuery's ajax error callback.
Figuring out why it's calling the error callback and not the success callback is harder. That statusText suggests that your server returned the string 'load' - is that a possibility? Another common problem is if your data isn't actually valid JSON. JSON's quite a picky format; if you're producing it yourself, you might have invalid whitespace or the wrong kind of quotes (or completely missing quotes). Check your data with a tool like JSONLint and make sure it's valid, and make sure that your server is only returning JSON - nothing else in the response body.
Just a work around
1. remove dataType:'json'
2. parse json in success function call
data = $.parseJSON(data);

errorThrown jquery error-callback function

What data is the parameter errorThrown (third parameter of jQuerys error callback function)
Is it something, that the server (backend one has written, in my case it is some REST-based services written in Java) has to return, or is it something more general, which is "automatically" returned without one has to add some error-handling in ones code?
Well, from jQuery.ajax()s documentation:
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )
... When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error."...
So the errorThrown string coorseponds to the HTTP status response for any failure responses (>399) For a 400, it would be Bad Request, 500: Internal Server Error, etc...
Quote from the documentation:
error
Type: Function( jqXHR jqXHR, String textStatus, String
errorThrown ) A function to be called if the request fails. The
function receives three arguments: The jqXHR (in jQuery 1.4.x,
XMLHttpRequest) object, a string describing the type of error that
occurred and an optional exception object, if one occurred. Possible
values for the second argument (besides null) are "timeout", "error",
"abort", and "parsererror". When an HTTP error occurs, errorThrown
receives the textual portion of the HTTP status, such as "Not Found"
or "Internal Server Error." As of jQuery 1.5, the error setting can
accept an array of functions.
So basically the errorThrown parameter has nothing to do with the response sent from the server. It's just the error reason associated to the status code. If your server uses custom error reasons in addition to setting the status code, this parameter might be useful to retrieve it.
Something to note (I just ran into this) is that errorThrown will be an empty string for requests that were made with HTTP/2.
This is because the property comes from the statustext property of the underlying XHR, and that property does not get populated for HTTP/2 requests.
More info here:
Why is the statusText of my XHR empty?

Ajax don't receives onError Message

In my aspx login script I don't get server Error messages via Javascript. I don't understand where the problem is or what's wrong.
The script sends an Ajax Response to this URL: login.aspx?ajax=true On error it receives a 403 Error Code with Error message. But the Error message could not been found in the data value. Are there some other parameters in VB that I have to send? Or have I made a mistake in the Javascript?
In Firebug I can see the Error message.
HTML
Login Fail. 3 tries left.
login.aspx
function onError(data) {
$('#errormessage').text(this);
$.mobile.changePage("#loginError", {
transition: "pop",
reverse: false,
changeHash: false
});
$("#Submit1").click(function() {
var formData = $("#loginform").serialize();
$.ajax({
type: "POST",
url: "login.aspx",
cache: false,
data: formData,
success: onSuccess,
error: onError
});
return false;
});
aspx.vb
Catch ex As AccessDeniedException
Response.StatusCode = 403
Response.Write(ex.Message)
'Response.AppendHeader("XML", "<xml><error>" + ex.Message + "</error></xml>")
'Response.StatusDescription = "<xml><error>" + ex.Message + "</error></xml>"
'Response.Status = ex.Message
Response.End()
From jQuery ajax documentation
error(jqXHR, textStatus, errorThrown)Function
A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests. This is an Ajax Event.
So if you want the HTTP status, put the errorThrown into the html, or dig it out of the jqXHR variable which you data variable currently represents.

Error notification not working

My problem happens to be the error, I am attempting to produce an error, in this case the error being hiding the loading symbol and showing a refresh button in order for the user to reload the page to see if the data loads this time.
$(document).ready(function () {
$('#busy').show();
$(document).bind('deviceready', function () {
var today = $('#todaysong');
$.ajax({
url: 'my url',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function (data, status) {
$.each(data, function (i, item) {
var song = '<name>' + item.name + '</name>' + '<artist>' + item.artist + '<br></artist>';
$('#busy').hide();
today.append(song);
});
},
error: function (error) {
$('#busy').fadeOut();
$('#reload').fadeIn();
}
});
});
});
This is my code, could someone advise on what I am doing wrong, I've tried a few things and cannot seem to get it to work, also would I make it so said button was able to refresh this individual piece of code?
Thanks a lot.
In order to debug your code:
Are you generating an error on your own? Is it really an error? Track your request via Firebug or ...
Be sure about running the error function. Again try Firebug or such things to set break points.
Check the JavaScript console for being sure there is no any of damn JavaScript error. And again Firebug error console.
Without seeing other details it is difficult to suggest.
Still I'm trying.. Check the IDs of the elements you have mentioned is same as they are in HTML. Check in HTML that one id is not assigned to more than one element.
In the AJAX code remove jsonp: 'jsoncallback', for a while and test if it is working.
error(jqXHR, textStatus, errorThrown)
A function to be called if the request fails. The function receives
three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a
string describing the type of error that occurred and an optional
exception object, if one occurred. Possible values for the second
argument (besides null) are "timeout", "error", "abort", and
"parsererror". When an HTTP error occurs, errorThrown receives the
textual portion of the HTTP status, such as "Not Found" or "Internal
Server Error." As of jQuery 1.5, the error setting can accept an array
of functions. Each function will be called in turn. Note: This handler
is not called for cross-domain script and JSONP requests. This is an
Ajax Event.
Where the important part in this case is;
Note: This handler is not called for cross-domain script and JSONP
requests.
Quote from the API documentation of jQuery.ajax.
You should instead be using jsonpCallback.

Categories

Resources