What does Dojo consider a XHR request error? - javascript

When doing AJAX through Dojo we can pass two callbacks, one to execute after a successfull request and one to execute after an error:
dojo.xhr("GET",{
url: myURL,
content: messageContents,
load: function(returnData, ioArgs){
//This is called on success
},
error: function(returnData, ioArgs){
//This is called on failure
}
});
I couldn't find in the documentation what is defined as an error. I'd guess anything with a return code >= 400 but I'm not sure.

Generally speaking, an unsuccessful HTTP response code. The determination is made by calling dojo._isDocumentOk which as you'll see basically accepts 2xx and 304 plus some browser-quirk stuff.

Related

how to handle jquery ajax success and failure correctly

So I have a jquery ajax call like so:
$.ajax({
url: 'delete.php',
data : {
'prd_id': <prd-id-number>
},
success: function(data) {
//show success here
},
error : function(error) {
//show error here
}
});
My doubt is about the success and error handlers. Is the error handler only used for "ajax level" error? I mean - my application can have its own error, for.e.g. the passed product id does not exist or is incorrect. Now, currently what I am passing a message back, which goes into success() then I have to do some internal logic to see if the message is an application error or truly success - and based on that I show the message.
is there any way I can send the message to error() - is that the proper way to trap and handle ajax errors?
Ajax error can be triggered several different ways. The most common ones are , http status not being 200, timeout and data parsing errors such as incorrectly formatted json.
You can trigger the error yourself from server by returning an http response code header.
For example assume you have an API that looks up users by ID and you send an invalid ID. You can return a 404 response code header with data included that can be used in your app from within the error callback.
This allows you to set up the application code to handle both types of errors using the error callback
Well i think you need to recall some concepts.
ajax success and error handlers are called depending upon the success or failure of the axaj call send.
success handler is called whenever the ajax call has successfully completed while error handler is called whenever the ajax call could not be completed due to any sort of error.
For your case you will have to manipulate the success handler and show the required message.
There is no way to call error handler when your ajax call has been successfully completed.

Unable to get the response from an ajax call in the success function

After refering this stack link Ajax response not calling success:function() when using jQuery 1.8.3 am wondering why if I uncomment the datatype line the success function is not invoked.I can understand that dataType =JSON is not calling success function.Could some one help me out ?
function doAjaxCall(methodType,Url,params,requestType,callBackFunction)
{
if(validate.variable(Url) && validate.variable(params))
{
$.ajax({
type : methodType,
url : Url,
// dataType : 'JSON', //if i uncomment i am not getting the response under success
data : params,
success : function(data)
{
console.log(data);
callBackFunction(data);
}
});
}
}
function callBackFunctiontest(data)
{
console.log('callBackFunctiontest : ' +data);
}
doAjaxCall('GET','/getData?accountNumber=9840100672&oid=d11c9f66-4c55-4855-a99e-580ba8ef8d61','noparams','application/JSON',callBackFunctiontest);
If it's not passing in success function, put an error function. This way you'll be able to see the error and understand what's going on.
You can also open the developer console and have a look at the 'network' panel.
Assuming you're calling callBackFunctiontest which should then be calling doAjaxCall.
You're trying to use data when there is no variable named data in scope. It will throw an undefined exception and doAjaxCall will not get executed. So your AJAX request will never get sent.
Try getting rid of the console.log('callBackFunctionTest : ' +data);, or pass it a value for data.
I am using Express JS web framework and NodeJS, both latest versions - 4.x.x.
Issue #1 - Not all of my POST ajax calls were being sent to my NodeJS server code.
How I found this is by trying to POST using Postman. All POSTMAN call requests were received by the server code but not the Express client requests. I checked by printing the console.log server debug statements to compare the findings between POSTMAN & Express Client.
Issue #2 - I was never receiving any response message from the server even though the server responded with a status 200 OK.
For both the issues, I made a few changes, which I believe will help others.
In the ajax call, I added e.preventDefault(); where 'e' is the event which is triggered via #click/#onclick.
Within ajax function call, I added the parameter dataType: 'json'.
In the NodeJS server code, index.js, I replaced res.send(req.body.search_data); with res.json(req.body.search_data);
P.S. - e.preventDefault() was actually built for a different purpose but it helped because it prevents a link from following the URL which is what solved the above issues.

jquery not properly handling the jsonp data from twitter api call

See the below code,I am trying to handle the error which is returned by the twitter api call. Remember Jquery do not handle jsonp datatypes and hence the timeout , the below code will obviously throw an error for a non existent twitter ID. I want to catch that error in my req.error method and show it to the user. But apparently , the error is hidden and does come to console.log('Oh noes!'+msg.error); This has surely something to do with the jquery handling jsonp type data. Has anyone encountered the same ? Any solutions ?
function findUserInfo(){
var req = $.ajax({
url: "https://twitter.com/users/show.json?id=neverexistID",
dataType : "jsonp",
timeout : 10000
});
req.success(function(msg) {
console.log('Yes! Success!'+msg);
});
req.error(function(msg) {
console.log('Oh noes!'+msg.error);
});
}
Answer:
jsonp calls are special and the errors thrown is usually hidden,and thats why I couldn't handle the error situation,the below plugin handles the situation well and solved my issue.
jsonp plugincode.google.com/p/jquery-jsonp
There is a workaround for your problem, change your url call to:
url: "https://twitter.com/users/show.json?suppress_response_codes&id=neverexistID",
From the Twitter documentation
suppress_response_codes: If this parameter is present, all responses
will be returned with a 200 OK status code - even errors. This
parameter exists to accommodate Flash and JavaScript applications
running in browsers that intercept all non-200 responses. If used,
it’s then the job of the client to determine error states by parsing
the response body. Use with caution, as those error messages may
change.

What/when does a call to the jQuery AJAX method return?

A little background:
I am trying to implement and AJAX powered SlickGrid. There isn't much documentation so I used this example as a base.
In this example there is the following code that hits the desired web service to get the data:
req = $.jsonp({
url: url,
callbackParameter: "callback",
cache: true, // Digg doesn't accept the autogenerated cachebuster param
success: onSuccess,
error: function(){
onError(fromPage, toPage)
}
});
req.fromPage = fromPage;
req.toPage = toPage;
I'm not exactly sure what jsonp does but from what i've read it appears to be very similar to the ajax method in jQuery except it returns json and allows cross domain requests. The webservice that I happen to be calling only returns XML so I changed this chunk of code to:
req = $.ajax({
url: "/_vti_bin/lists.asmx",
type: "POST",
dataType: "xml",
data: xmlData,
complete: onSuccess,
error: function (xhr, ajaxOptions, thrownError) {
alert("error: " + xhr.statusText);
alert(thrownError);
},
contentType: "text/xml; charset=\"utf-8\""
});
req.fromPage = fromPage;
req.toPage = toPage;
My issue is that my page errors out at req.fromPage = fromPage; because req is null.
Am I wrong to think that I can just replace my jsonp call with a call to the ajax method? Is req just not set because my ajax call hasn't finished by the time that code is executed? How can I get around either of these issues?
If I comment out the last two lines and hard-code those values elsewhere everything runs fine.
Am I wrong to think that I can just replace my jsonp call with a call to the ajax method?
No, that should work just fine.
Is req just not set because my ajax call hasn't finished by the time that code is executed?
Yes, that is correct.
The ajax methods starts the request and returns immediately. If you want to do something after the response has arrived you should do that in the success event handler.
You might actually want to use the success event instead of the complete event, as the complete event happens even if there is an error.
You could specify async: false, in your settings to make the ajax call wait for the response, but that means that the browser freezes while it's waiting.
As Guffa stated, $.ajax() works asynchronically. Thus, you have to specify a callback that will be called when the request has returned a response, rather than to just use whatever $.ajax() returns.
There are a couple of different callback methods you can specify:
complete - runs when you recieve a response, regardless of its status.
success - runs when you recieve a response with a successful status code (usually 200).
error - runs when you recieve a response with an error code (for example 404 or 500).
To do something with the response body after a successful request, you should do something like
$.ajax({
...
success: function(body) {
alert('This is the method body:' + body);
}
});
Read up in the documentation on the different methods to see what more parameters you can use.

Catching a JSONP error on a cross-domain request

I'm using jQuery.getJSON() on a URL (different domain) which may not exist. Is there a way for me to catch the error "Failed to load resource"? It seems that try/catch doesn't work because of the asynchronous nature of this call.
I can't use jQuery.ajax()'s "error:" either. From the documetation:
Note: This handler is not called for cross-domain script and JSONP requests.
If you have an idea of the worst case delay of a successful result returning from the remote service, you can use a timeout mechanism to determine if there was an error or not.
var cbSuccess = false;
$.ajax({
url: 'http://example.com/.../service.php?callback=?',
type: 'get',
dataType: 'json',
success: function(data) {
cbSuccess = true;
}
});
setTimeout(function(){
if(!cbSuccess) { alert("failed"); }
}, 2000); // assuming 2sec is the max wait time for results
This works:
j.ajaxSetup({
"error":function(xhr, ajaxOptions, thrownError) {
console.log(thrownError);
}});
Deferred objects (new in jQuery 1.5) sound like exactly what you're looking for:
jQuery.Deferred, introduced in version 1.5, is a chainable utility object that can register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.
http://api.jquery.com/category/deferred-object/
EDIT:
The following code works fine for me:
function jsonError(){
$("#test").text("error");
}
$.getJSON("json.php",function(data){
$("#test").text(data.a);
}).fail(jsonError);
json.php looks like this:
print '{"a":"1"}';
The error function fires for me if the path to json.php is incorrect or if the JSON is malformed. For example:
print '{xxx"a":"1"}';
What your complaining about is a client-side error saying that you tried to download a resource from the server.
This is build into the browser and it allows your browser to tell the client or the developers that the downloading of a resource from the internet failed. This has nothing to do with JavaScript and is a more low level error thrown on the HTTP that is caught by the browser.
If you want any hope of catching it your going to need to drop 3rd party ajax libraries and deal with the XMLHTTPRequest object on a much lower level, even then I doubt you can do anything about it.
Basically when you see this error then find out what object your trying to get that doesn't exist or couldn't be accessed. Then either stop accessing it or make it accessible.

Categories