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

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);

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)

Sending a json object using ajax to a servlet and receiving a response json object

I'm trying to send a json object using ajax to a servlet. The object is to be changed and sent back to the client. This is the code I used to send the json object from client to server.
function sendJson(jsonObj)
{
var parsed = JSON.parse(jsonObj);
$.ajax({
type: 'get',
url: 'GameLogic',
dataType: 'JSON',
data: {
loadProds: 1,
parsed: JSON.stringify(parsed)
},
success: function(data) {
},
error: function(data) {
alert('fail');
}
});
}
I only have a basic knowledge of javascript. As I understand this piece of code just sends a json object to a servlet. When receiving the response from the servlet, how do I get it? I searched for this and found functions similar to above function to receive response. I don't understand what this success: function(data) part does.
Can someone explain me the way to send a json object and receive the response to and from a servlet.
When I send a json object to the servlet, is there any way I can know whether it is received by the servlet, other than sending the object back as the response.
Ver simply, the answer is already in your code.
The ajax method of jquery has to callback methos for success and error.
Both are already impl. in your example but doing nothing!!
Here your code with comments pointing to the callback impl.
{
var parsed = JSON.parse(jsonObj);
$.ajax({
type: 'get',
url: 'GameLogic',
dataType: 'JSON',
data: {
loadProds: 1,
parsed: JSON.stringify(parsed)
},
success: function(data) {
// PROCESS your RESPONSE here!!! It is in "data"!!!!
},
error: function(data) {
// This is called when the request failed, what happend is in the "data"!!!
alert('fail');
}
});
}
Impl. something in the success callback and debug it with your browser dev tools to see what's inside of "data".
As you changed your question more about how to handle the communication in general and how to know if your request was received. Here my normal approach.
First I define an envenlope for every request and response which is always the same. It can look like this:
{
status: OK | ERROR,
message: "possible error message etc."
data: JSON Object representing the payload.
}
After doing this I can impl. a generic logic to send and receive message between server and client and every side nows how to handle the envelope. To make sure a message is received, could be processed etc.
Then you have this:
Make an ajax call to your server.
2a. If there is topoligical problem your error callback on client side is called. Request failed, server not reachable!
2b. The message was received by the server. The server can now process the payload regarding the URL used to call the server. The server method succeed it will write an OK in the envelop and his possible result in "data" as payload. If the method fails, it sets "status" to "ERROR" and provides an proper message, data is empty.
The client receives data on the success callback and it can inteprete the "status" field if it's a usefull response or if it's an error.
Hope that helps
The success:function() part goes like this
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
the jqXHR (jQuery-XHR) object
What this means is - if your ajax request was successful, the server will return you some response, ie, the data. This "data" can be used in the function.
$.ajax({
...
success: function(data) {
// process the "data" variable
console.log("SERVER RESPONSE");
console.log(data);
}
});

JSON object returned but not accessible via $.ajax()

I have an ASP.NET MVC Web API that I am calling from an $.ajax() method. The correct JSON is returned from my API, but the object is not accessible. The error received in my console when trying to log the value for "Name" is:
Uncaught TypeError: Cannot read property 'Name' of undefined
JSON:
[{"id":2,"Name":"thom","Picture":"thom.jpg","About":"I'm a guy. This is my profile. Now quit staring and get out of here.","Location":"London"}]
jQuery:
$.ajax({
cache:false,
type: 'GET',
dataType: 'json',
url: 'http://localhost:3235/Users/searchUsers?callback=?&searchString=' + searchString,
complete: function (data) {
console.log(data[0].Name);
}
});
Any help would be appreciated. Thanks!
I think you mean to use the success function. The complete function doesn't take data as a parameter.
From the docs:
completeType: Function( jqXHR jqXHR, String textStatus )A function
to be called when the request finishes (after success and error
callbacks are executed). The function gets passed two arguments: The
jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string
categorizing the status of the request ("success", "notmodified",
"error", "timeout", "abort", or "parsererror").
The method's first parameter is not the received data. You can get it though the jqXHR object but I don't think you really need to use this option. Use success instead:
success Type: Function( PlainObject 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; a
string describing the status; and the jqXHR (in jQuery 1.4.x,
XMLHttpRequest) object.
ya complete fires after the service call is being made and it does not contain data from the service response..
use
$.ajax({
url:'ur url',
type:'GET'
success:function(data){
// way to acces ur object code goes here
console.log(data[0].Name);
},
error:function(){
// Error handling
}
});
happy coding

Json Response is undefined

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.

how to get jquery ajax status code

I want to know that how can we get ajax status code in jquery.
I have this ajax block:
$.ajax{
type: "GET",
url: "keyword_mapping.html",
data:"ajax=yes&sf="+status_flag,
success: callback.success,
complete: rollup_filters(),
failure: function(){
alert("Failure");
}
}
Now in above code, in case of failure, how can i get ajax status code and some description of that status code ??
You want to use the error option to capture this. For example:
error: function (jqXHR, textStatus, errorThrown)
// Your handler here...
}
You can then use the jqXHR object to retrieve information about the failure.
From the documentation:
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()
abort()
First, you have a few syntax errors. The above is a method call, so it needs to follow $.ajax({ ... }); (with parenthesis).
Secondly, you want to supply the error property as part of the object, not failure (see docs for more information).
Third, when you do bind to an error, you are supplied three parameters: jqHXR, textState, errorThrow. These arguments will supply you the details of a failed AJAX call. (More specifically, try jqXHR.status)
Alternatively, you can bind to the $.ajaxError function as well.
Update To keep this more up-to-date, you should now be following the Deferred API (as of jQuery 1.5), which would make binding to an error look something like the following:
$.ajax({ /* options */ })
.done(function( data, textStatus, jqXHR ){
// here you bind to a successful execution.
.fail(function( jqXHR, textStatus, errorThrown ){
// Here you can catch if something went wrong with the AJAX call.
})
.always(function(){
// here you can execute code after both (or either) of
// the above callbacks have executed.
});
Change your failure callback to
error:function (xhr, options, error){
alert(xhr.status);
alert(error);
}
There is nothing like failure in ajax settings. Replace failure by error and you get 3 arguments in the error callback. First argument is the xhr object which has a status property in it.
$.ajax{
type: "GET",
url: "keyword_mapping.html",
data:"ajax=yes&sf="+status_flag,
success: callback.success;
complete: rollup_filters(),
error: function(jqXHR, textStatus, errorThrown){
alert(jqXHR.status);
}
}

Categories

Resources