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';
Related
I'm using WebvoltyTemplate that utilizes it's own search template but it also is responsible for filtering products. Every time I try to search for a product in main searchbar and also when I try to show filter list with a simple button it uses ajax request. The problem is that every time it throws an error.
POST https://www.example.com/modules/wtcmssearch/ajax.php? 403
send # core.js:39
ajax # core.js:39
error wtcmssearch.js:62 error
The 'error' message comes from that part of code that doesn't actually tell anything.
$(document).on('keyup','.wtcmsheader-search .wtsearch-header-display-wrappper .wtheader-top-search .wtheader-top-search-wrapper-info-box .wtcmssearch-words',function(){
var obj = $(this).parent().parent().parent().parent().find('.wtsearch-result');
obj.html('');
obj.show();
var search_words = $(this).val();
var cat_id = $('.wtcms-select-category').find('.selected').val();
if (search_words.length != 0) {
$.ajax({
type: 'POST',
url: baseDir + 'modules/wtcmssearch/ajax.php?',
cache: false,
data: 'search_words='+ search_words + '&category_id='+ cat_id +' &token=' + static_token,
success: function(data)
{
obj.html('');
obj.append(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
});
The core.js function that throws an error is a very long one-liner:
function(e){var t,n,r,i,o,a,s,u,l,c,d,f,p,h,v,m,g,y,x,b="sizzle"+1*new Date,w=e.document,T=0,C=0,k=oe(),S=oe(),j=oe(),_=function(e,t){return e== .....................
Every file has right permissions set. I have no idea where should I start looking for a problem root. Any idea?
EDIT:
I have found out that another feature doesn't work because of that- adding to wishlist. It Also throws an error in core.js:39. I would like to send the whole line but it's about 83k characters.
EDIT 2:
I noticed that when I try to look up the ajax.php file through my browser it also throws an 403 exception. No idea how to investigate further. I turned of apache mod_security, didn't help.
I am working on a CI project, and for that, I have created a virtual host in wamp. It's working good. But the main problem started now. Whenever I call Ajax request it with/without giving the ajax post URL it shows a result. I don't know what is the issue..
I am clicking on forgot password link and then it opens a popup with forgot password form.
Without URL
$.get('').done(function (msg) {
console.log('Yes');
console.log(msg);
}).fail(function (xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
});
Result
In this case I am getting the result (it's going in "done") but giving me the whole login page HTML.
With URL
$.get('http://fileupload.local/login/getresetpassword').done(function (msg) {
console.log('Yes');
console.log(msg);
}).fail(function (xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
});
Result
I have tried too many solutions over google, but couldn't find the right one. Now I am pulling my hair and want to complete it.
Your Ajax looks ok to me. It should work. I have some suggestions:
Open directly Url: http://fileupload.local/login/getresetpassword in your browser. We will see the result (Seem that it will return the whole page?)
Check the server code. I think it's our main issue. Will it return the JSON type or not?
It was a config issue. It resolved by just change $config['uri_protocol'] = 'QUERY_STRING'; to $config['uri_protocol'] = 'REQUEST_URI';
I am presently developing a web application with jQuery mobile. However, I found that when a "changePage" fails, I can no longer send ajax requests. After the failure, all ajax requests return an error. Here's the code executed when the submit button on the form is clicked (it's a basic user login screen):
// Event when user click the Submit login button
$('#submitLogin').on("click", function () {
// submit the user credentials to the server
$.ajax({
type: "POST",
url: "./LogUser",
data: {
EmployeeID: $('#EmployeeID').val(),
EmployeePIN: $('#EmployeePIN').val()
},
dataType: "text",
async: true,
cache: false,
error: function (rqst, text, thrownError) {
$('#dlg-login-error-message').text(thrownError);
$('#dlg-login-error-popup').popup("open");
},
success: function (data) {
if (data == "Success") {
$.mobile.changePage("./LoadScreen/Menu");
}
else {
$('#dlg-login-error-message').text(data);
$('#dlg-login-error-popup').popup("open");
}
}
});
return false;
});
If the post itself fails, I can resubmit without problem. If the .mobile.changePage fails, a "page not found" is displayed, but I am not able to resubmit, ajax no longer making request to the server and jumping directly to the error callback with a "not found" error.
I am guessing the problem comes from the fact that jQuery mobile uses AJAX request to load pages, and that somehow, ajax calls are getting mixed up somewhere.
I did more tests, even intercepted the pageloadfailed event, but nothing works. After the page change failure, AJAX calls no longer sends anything to the server and jump automatically to the error callback function.
I tried with async=false, same problem. I tried debugging jQuery-mobile, but I am still not able to find the "changePage" function itself ( the .code is quite confusing ).
I just spent the last two days trying to figure out a way to resolve this and I am seriously thinking of using something else than jQuery-mobile for our development.
I have found a workaround for my problem, but I do not know the full impact of this solution yet.
To prevent the problem, I had to set the "pushStateEnabled" configuration option to "false".
So if you find yourself with the same problem, try putting the following in a script right before the loading of the "jQuery-mobile" script.
$(document).bind("mobileinit", function () {
$.mobile.pushStateEnabled = false;
});
Example:
<!-- Load the script for jQuery -->
<script src="~/Scripts/jquery-2.1.4.js"></script>
<!-- Set default for jQuery-Mobile, before it is actually loaded -->
<script>
$(document).bind("mobileinit", function () {
$.mobile.pushStateEnabled = false;
});
</script>
<!-- Load the script for jQuery-Mobile -->
<script src="~/Scripts/jquery.mobile-1.4.5.js"></script>
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)
Can any one help me with the following code:
$(document).ready(function() {
$("#add_user").submit(function() {
$.post( "../php/register_sql_ins.php",
{r_fname: $("#fname").val(),
r_lname: $("#lname").val(),
r_uname: $("#uname").val(),
r_pass: $("#pass").val(),
r_authLevel: $("#authLevel").val(),
r_email: $("#email").val(),
r_company: $("#company").val(),
r_phone: $("#phone").val(),
r_address: $("#add").val()}, function(result) {
alert(result);
}
);
return false;
});
});
This should store my user data in a sql table. the php part of code(register_sql_ins.php) works fine. but this query piece of code just doesn't work!! and I have no idea what is the problem!
With Firebug it returns false every time!
By the way sorry for bad english. It's not my mother tong!
There are two places where I would look for the cause of such error:
Network tab in Firebug. Check what is sent to the server and what is the response. If data sent is correct and server replies with status 200, then you have to debug your PHP script, else
Server logs. If the request failed to complete succesfully, log will contain the reason.