Ajax Error Handling - Success and failure - ajax

We will face 4 errors
Server side error (page not found)
Run time error (nullpointerexception)
Business error (specified name doesn't exist)
Form validation errors (Invalid input)
There are two functions available in each ajax call. success and failure calls
ex:
$.ajax({
success: function(){
},
error: function() {
// ????
}
});
Does failure handles all above of the above?
Does failure will gets called in all of the above cases ?
Thank.s

Related

Custom Error Message after Datatables ajax exception

I am displaying a table of data using datatables 1.10.12. The user can specify input parameters that cause an error on the server. An appropriate error message should be displayed to the user so they can modify their setup, however the only error options seem to be:
SHow the following generic error in an alert: "DataTables warning: table id=trackingTable - Ajax error. For more information about this error, please see http://datatables.net/tn/7"
Show the generic error in the browser console
Modify the server to return no rows, that is fail silently.
Does anyone know how to show a custom error after a datatables ajax request fails?
The following code sample is taken from the datatables documentation. Datatables handles the ajax call and handles success and error.
$(document).ready(function() {
$('#example').DataTable( {
"ajax": '../ajax/data/arrays.txt'
} );
} );
A 4th option I could add to the list would be to modify the datatables source code to handle the an error response myself. Which I'm not that keen on.
This question was asked in 2015 however it did not get an answer. See:
display server side exception
If you pass an object to the ajax property you can override the jQuery.ajax() error method:
$(document).ready(function () {
$('#example').DataTable({
ajax: {
url: '../ajax/data/arrays.txt',
error: function (jqXHR, textStatus, errorThrown) {
// Do something here
}
}
});
});
https://datatables.net/reference/option/ajax#object
This will stop the standard error message in the alert box.
Please note, it is not recommended to override the success method of jQuery.ajax() as it is used by DataTables.
You can implement your own custom error message globally like the example below.
$(document).ready(function() {
$.fn.dataTable.ext.errMode = () => alert('Error while loading the table data. Please refresh');
$('#example').DataTable( {
"ajax": '../ajax/data/arrays.txt'
});
});
Answering just in case someone is still looking for a solution.
In my case, I did the following
At server side set DataTablesOutput object.setError("ErrorMsg")
In my js method $.fn.dataTable.ext.errMode = 'none'; to avoid the error popup.
Created an error div in my page to display the custom error message
Added the below to my js method to handle error
$('#myDataTable')
.on('error.dt',
function(e, settings, techNote, message) {//Logic to set the div innertext
}
try {
$.ajax({
-------
-------
success: function (data){
//ShowDataTable is a js Function which takes ajax response data and display it.
ShowDataTable(data);
},
//this error will catch server-side error if request fails
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
ShowDataTable(null);
}
})
}
//this catch block will catch javascript exceptions,
catch (Error) {
if (typeof console != "undefined") {
console.log(Error);
ShowDataTable(null);
alert(Error);
}
}
EDIT
If you are willing to accept the error (for example if you cannot alter the backend system to fix the error), but don't want your end users to see the alert() message, you can change DataTables' error reporting mechanism to throw a Javascript error to the browser's console, rather than alerting it. This can be done using:
$.fn.dataTable.ext.errMode = 'throw';

$http error Function not showing error message

I have to give user a proper message while ajax call got fail
My Ajax call is as follows:
$http({
method:'PUT',
url:"/myapp/web/update",
crossDomain:true,
data:dataobj,
headers:{
'Content-Type':'application/json',
}
}).success(function (data) {
console.log("error"+JSON.stringify(data));
}).error(function (data, status, headers, config) {
console.log("error"+JSON.stringify(data));
});
from the backed i have used Spring MVC 4 as restfull api. From that i am validating the data and send response accordingly. If something went wrong in validation i throw custom exceptions.
Now if i throw just exception it got cached in Ajax success function but i want it to have to catch this in error function. for this i add following line of code :
response.sendError(500);
Now it got cached in error function as expected but i cant find JSON error message with it. Can anybody tell where i went wrong in the code.
Edit:
Following is the Code where i am responding with error message
#ControllerAdvice
public class ExceptionHandlingController{
#ExceptionHandler(EmployeeNotFoundException.class)
public #ResponseBody ExceptionJSONInfo handleEmployeeNotFoundException(HttpServletRequest request, Exception ex){
ExceptionJSONInfo response = new ExceptionJSONInfo();
response.setUrl(request.getRequestURL().toString());
response.setMessage(ex.getMessage());
response.sendError(500);
return response;
}
}

NS_Binding_Aborted error for ajax function

I have a link on click of which a request should go to web server and on successful execution a redirection should happen. I have used ajax for this but I am getting NS_Binding_Aborted error in HTTpFox.
The code:
<a id="lnkredirect" href="javascript:void(0);" onclick="myfunction();">Some text</a>
The ajax code:
function myfunction(){
$.ajax({
url: Web server Url,
type: 'POST',
datatype: 'JSON',
timeout: 20000,
data: null,
success: function{ $("#lnkredirect").attr('href','redirection link...');},
error : function{ $("#lnkredirect").attr('href','redirection link...');}
)};
return true;
}
The redirection is happening but I am getting NS_Binding_Aborted error in Firefox. In both success and error scenario, the redirection should happen but why NS_Binding_Aborted is coming, I am not sure of this. NS_Binding_Aborted error should come only if one event is cancelling some prior running event but I have already suppressed href of the link and redirecting it once the ajax request is executed, so there should be only one server call and NS_Binding_Aborted should not come. Please let me know where am I going wrong?
I got a similar trouble, also while using both a href and a XmlHttpRequest inside a onclick. My XMLHttpRequest was aborted (ns_binding_aborted) and thus never reached status 200. I also could see that my XHR was "blocked by devtools" in Firefox console.
This was because the page was reloaded (by the href) before it could finish its job (what was in the onclick).
I had something like this:
<script type="text/javascript">
function incrementNumberOfDownloads() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) { // 4 = request ended, 200 = success
//update displayed number of downloads
document.getElementById("numberOfDownloads").innerHTML = this.responseText;
}
};
xhttp.open("GET", "incrementNumberOfDownloads.php", true);
xhttp.send();
return true;
}
</script>
<p id="numberOfDownloads">42</p>
Download my file !
I fixed the problem by adding a target="_blank" to my download link, so that the page is no more reloaded when clicking, enabling the XMLHttpRequest to finish with success.
This is caused by another request that abort your request. Generally when your goal is reload data o all page just end request and don'ts is synchronized request, a little novell error.
In this case the "return " sentence is the problem, the return sentence must be in success seccion.
My issue fixed, when I've changed calling native js form submit event to jQuery submit event.
// this code
form[0].dispatchEvent(new Event("submit"));
// changed to
form.submit();

Access to HTTP response in Ext.data.Model.save() callbacks using REST proxy

I successfully implemented client editors and a server side API.
Now I'm adding more validation at the server side, and besides returning the proper HTTP code (200 for OK, 4xx for other uses, 500 for errors, etc.) I want to return a list of validations that failed after the submission generated by Model.save().
I run it this way:
myModel.save({
success: function (a, operation, c) {...},
failure: function (a, operation, c) {...}
});
But if there was a failure, the operation object only have the response status and its statusText, all through
operation.error.status // i.e. 409
operation.error.statusText // "Conflict"
But server side a detail of the failing validations (mostly domain level ones) are being added to the response.
Is there a way I can get what the server sent as the body of the HTTP response to the PUT/POST submission?
Do I have to return it using a particular JSON structure?
EDIT:
I'm now returning this as the body of the HTTP Response (with code 4xx):
{
data: {/* the record serialized */},
success: false, // or true if everything went ok
message: "This failed because X and Y."
}
Thanks in advance.
For some reason Ext is not attaching the response content to the error object, but it triggers an exception event if there is a failure.
So what we did was to handle the "exception" event of the model's proxy, and then we will have access to the XHR response, being able to do whatever we want with it.
myModel.getProxy().on('exception', this.onProxyException, this);
The handler is as follows:
onProxyException : function (proxy, response, operation) {
var errors;
errors = Ext.JSON.decode(response.responseText).message;
/* Whatever is needed with the errors */
}
In this example we asume the errors come in JSON format, they could be a simple text string, which wouldn't require the use of decode().
According to this blog:
http://code.tonytuan.org/2013/07/extjs-get-server-response-in-modelsave.html
You can write code like this:
model.save({
success: function (record, operation) {
// json response from server
console.log(operation.response);
},
failure: function (record, operation) {
// undefined
console.log(operation.response);
// json response from server
console.log(operation.request.scope.reader.jsonData);
}
});
in reader block add: messageProperty: 'message'
from server return: success:false, message: 'error test'
from failure get error:
failure: function (records, operation) {
Ext.Msg.alert('error', operation.error);
}

Error handling when downloading a file from a servlet

I have a web application that must work with IE7 (yeah i know..) where the frontend is entirely made with ExtJS4, and theres a servlet used to download files. To download a file i send some parameters so i cant simply use location.href. it must be a POST.
So far it works, but when an exception is thrown in the servlet i dont know how to handle it to show the user some alert box or some message without redirecting to another page.
In my webapp im also using DWR and im aware of the openInDownload() function, but it triggers a security warning in IE.
So, (finally!) the question is
Using this code:
post = function (url, params) {
var tempForm=document.createElement("form");
tempForm.action=url;
tempForm.method="POST";
tempForm.style.display="none";
for(var x in params) {
// ...snip boring stuff to add params
}
document.body.appendChild(tempForm);
tempForm.submit();
return tempForm;
}
is it possible to stay in the same page after submitting ?
or with this other one:
Ext.Ajax.request({
url: './descargaArchivoNivs',
method: 'POST',
autoAbort: true,
params: {
nivs: jsonData
},
success: function(response){
// HERE!!
// i know this is wrong
document.write('data:text/plain,' + response.responseText );
/* this looked promising but a warning pops up
var newwindow = window.open();
newwindow.document.open();
newwindow.document.write('data:text/plain, ' + response.responseText );
newwindow.document.close();*/
},
failure: function(resp){
alert('There was an error');
}
});
is it possible to open the file download dialog // HERE!! with the response content??
or is there some other way to open the file download dialog on success, and on failure show a friendly message without losing the users input (the params of the POST) ?
(sorry if this post was too long)

Resources