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.
Related
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.
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.
Background:
Using jQuery 1.7 client side
PHP server side
Using json responses with json_encode php function
The content-type header is correct, any of these works: text/plain,text/x-json,application/json.
There's no errors thrown from my php code
Am working on Firefox 11
Am using the js console and the other web's developer tools
HTTP/1.1 200 OK
In this Javascript code, the success event is never fired:
$.ajaxSetup({cache:false,
success:function(d) {
console.log("ok from setup with data "+d.toSource())
},
complete:function(xhr,ts){
console.log("Ajax finished reponse:"+xhr.responseText)
},
error:function(jqXHR, textStatus, errorThrown){
console.log("Error")
}
});
$.getJSON("test2.php",{},function(data){
//some code here
});
When I do it this way, it works:
$.ajaxSetup({cache:false,
complete:function(xhr,ts){
console.log("Ajax completado con:"+xhr.responseText)
},
error:function(jqXHR, textStatus, errorThrown){
console.log("Error")
}
});
$.getJSON("test2.php",{},
function(data){
//some code here
}).success(function(d){
console.log("success applied directly, data "+d.toSource())
}
);
In both cases the complete event is always fired and the error one never.
However, in the second code the success is fired.
Obviously for .get() method it's the same.
PHP code:
<?php header("Content-Type:application/json;charset=utf-8");
//or whatever text/x-json text/plain, even text/html, jquery do the dirty job
echo json_encode(array("stat"=>"1")) ?>
My objectives:
I want to fire the same success event to all ajax requests
I want to use the json data returned by the request in my success event, and if it is possible, without convert the raw jqXHR responseText to a json again
The problem is strange, any ideas?
I read all these questions:
Ajax success event not working
AjaxSetup never execute the success function
Does jQuery ajaxSetup method not work with $.get or $.post?
$.ajax function's success: not firing
And I'm pretty sure none of them are my problem.
Take a look at the ajaxSetup documentation: http://api.jquery.com/jQuery.ajaxSetup/
Note: Global callback functions should be set with their respective
global Ajax event handler methods—.ajaxStart(), .ajaxStop(),
.ajaxComplete(), .ajaxError(), .ajaxSuccess(), .ajaxSend()—rather than
within the options object for $.ajaxSetup().
I think that's your problem right there.
UPDATE
If you want your ajax handlers to be global for any ajax request on the page, do something like this:
$(document).ajaxSuccess(function(d){
console.log("ok from setup with data "+d.toSource());
});
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.
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.