Angular.js
$scope.exportTable = function (param, isId) {
//var excelContents = JSON.stringify( $((isId) ? "#"+param:"."+param).html());
console.log(JSON.stringify($((isId) ? "#" + param : "." + param).html()));
$interval($scope.downloadExcel(JSON.stringify($((isId) ? "#" + param : "." + param).html())), 3000);
};
$scope.downloadExcel = function (excelContents) {
console.log("this should be displayed after 3 seconds");
$.ajax({
url: urls.BASE_API + "user/setExcelContents",
data: {excelContents: excelContents},
type: 'POST',
dataType: 'json',
complete: function (data) {
if (data.responseText == "1") {
window.location.href = urls.BASE_API + "user/exportExcel";
}
}
});
};
Here I'm trying to send 1600 table rows to a controller method in Java, which then I will catch the param with #RequestParam('excelContents')
This throws error on Request parameter is not present
Now, If i send like 20-50 table rows, this works fine without any errors.
I was thinking that JSON.stringify() can't complete its task BEFORE I send it as the parameter, so thats why I added the $interval, but $interval doesn't work. it doesn't pause for 3 seconds (3000 milliseconds) when I pass the argument. The method runs as soon as I call it, without any pausing.
Related
I make a post request to my rest controller and as a result I want to get information about the error in case of incorrect data. Error information is generated in #RestControllerAdvice.
Here is my advice class:
#RestControllerAdvice
public class RestControllerErrorHandler {
#ExceptionHandler(MethodArgumentNotValidException.class)
#ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, Object> handleCustomerException(MethodArgumentNotValidException exception) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("timestamp", new Date());
body.put("exception", "MethodArgumentNotValidException");
List<String> errors = exception
.getBindingResult()
.getFieldErrors()
.stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toList());
body.put("errors", errors);
return body;
}
}
Here is the result of the error that I get.
{
"timestamp": "2020-07-07T20:20:44.778+00:00",
"exception": "MethodArgumentNotValidException",
"errors": [
"Login length: 6 - min and 10 - max",
"Password length: 6 - min and 10 - max"
]
}
This is how I call method POST from ajax:
$(document).ready(function () {
$("#sendForm").click(function () {
const login = $('input[name=login]').val();
const password = $('input[name=password]').val();
$.ajax({
type: "POST",
url: "/api/users",
contentType: 'application/json',
data: JSON.stringify({"login": login, "password": password}),
dataType: "json",
success: function (data) {
alert('success: ' + data.id + " " + data.login + " " + data.password)
},
error: function (requestObject, error, errorThrown) {
alert(error);//this field return "error" string
alert(errorThrown);//for some reason this is empty when I get an error
}
});
});
});
How can I read it to get exactly the error information? I want to display this: "Login length: 6 - min and 10 - max", "Password length: 6 - min and 10 - max" in alert().
so, what you should note - the response is an object (array-like) which has a subkey named errors which itself contains the data (non-keyed array). So, you should change the Ajax success part to this:
success: function (data) {
var parsed_response = JSON.parse(data);
alert(parsed_response.errors[0]+ " " + parsed_response.errors[1]);
},
as you see, with parsed response, you get the access to the members of the object.
update:
if you want to get the error response, that it means the "response object" (which contained timespamp, exception, errors... members) you had prepared for your response, doesnt matter, as it will not be returned in that (erroneus) situation. So, in that case, as you already mentioned, you are getting alert of the error message, and depending on that (i.e. 404, 410, ...) it will tell you what happens on backend. you will not get any response in that case, because "error" function itself says that server didn't return the readable (outputed) answer, and you have to fix that error (i.e. 410, 503 or whatever, search for them in google).
I might also suggest to save debug file in backend language when receiving the ajax request, so you will find out in which line the backend code breaks.
i.e.
save_to_file("a1");
your codes
save_to_file("a2");
your another codes
save_to_file("a3");
and so on...
so, some of the backend code has error.
found a solution:
error: function (requestObject, error, errorThrown) {
const result = JSON.parse(requestObject.responseText);
alert('error: ' + result.errors[0]);//"Login length: 6 - min and 10 - max"
}
I'm using FullCalendar to render events on the calendar (in a JSP), but not working in IE (only in IE).
I do an ajax request and, with the json that is returned, create an event to render the calendar as follows:
$.ajax({
type: "POST",
url: 'criarTreinoJson'+params,
dataType: 'json',
contentType: 'application/json',
success: function(data) {
var treino = data.treino;
var newEvent = {
title: treino.local.name,
allDay: true,
start: treino.date.year + "-" +
treino.date.monthValue + "-" +
treino.date.dayOfMonth
};
$('#calendar').fullCalendar( 'renderEvent', newEvent, true);
}
});
jQuery = v2.1.3, FullCalendar = v2.3.1.
In the backend I use Struts 2 + Spring with Java 8.
The problem is the formatting of the date.
I'm using java.time.LocalDate and monthValue and dayOfMonth attributes return single digits if the value is less than 10, and it does not work in IE.
i. e., "2-5-2016" does not work in IE, the right is "02-05-2016".
To correct the problem, i changed it:
start: treino.date.year + "-" +
treino.date.monthValue + "-" +
treino.date.dayOfMonth
For this:
start: treino.date.year + "-" +
(treino.date.monthValue<10?"0"+treino.date.monthValue:treino.date.monthValue) + "-" +
(treino.date.dayOfMonth<10?"0"+treino.date.dayOfMonth:treino.date.dayOfMonth),
In my application I need to pass an array of parameters form client side to server side. I tried the following code but its not working.I need to get data from checkbox list and pass it to server side.
My code for the client side
$(".add").click(function(){
monitoring.length=0;
nonMonitoring.length=0;
$('.modal-body input:checked').each(function() {
monitoring.push($(this).val());
});
$('.addkeywords input:checked').each(function() {
nonMonitoring.push($(this).val());
});
// alert(monitoring[2]+ " " + nonMonitoring[2]);
var monitoringLength=monitoring.length;
var nonMonitoringLength=nonMonitoring.length;
$.ajax({
type : "GET",
url : '/rest/my/rest/mysql/controller',
data : {
monitoringLength: monitoringLength,
nonMonitoringLength: nonMonitoringLength,
monitoring : monitoring,
nonMonitoring: nonMonitoring,
},
success : function(data) {
// var keywordsList=data
//console.log(keywordsList);
// htm = "" ;
if(data=='success'){
// loadChannels();
location.reload();
}else{
alert("failed to upload");
}
}
});
})
My code for the server side.
#RequestMapping("/rest/my/rest/mysql/controller")
public void monitorKeywords(#RequestParam(value="monitoringLength",required=true)int monitoringLength,#RequestParam(value="nonMonitoringLength",required=true)int nonMonitoringLength,#RequestParam(value="monitoring",required=true)List<String> monitoring,#RequestParam(value="nonMonitoring",required=true)List<String> nonMonitoring){
System.out.println("MonitoringLength =>" +monitoringLength);
System.out.println("NonMonitoringLength=>" +nonMonitoringLength);
System.out.println("Monitoring=>" +monitoring);
System.out.println("Monitoring=>" +nonMonitoring);
Somehow this is not working.What is the error in this? Please help
In Request parameter change List to array
i.e.
#RequestParam(value="monitoring",required=true) String[] monitoring, #RequestParam(value="nonMonitoring",required=true) String[] nonMonitoring
Actually I've been reading about this for a while but I couldn't understand it very well.
Here is a snippet of the Servlet "ProcessNurseApp" :
if (dbm.CheckExRegNumber(Candidate.getRegNumber()) == true) {
// Show him an alert and stop him from applying.
out.println("<script>\n"
+ " alert('You already Applied');\n"
+ "</script>");
out.println("<script>\n"
+ " window.history.go(-1);\n"
+ "</script>");
}
So when the form named "ApplicationForm" in the "Nurses.jsp" get submitted it goes to that method in servlet after some Javascript validation.
My issue is that I want to call that method
if (dbm.CheckExRegNumber(Candidate.getRegNumber()) == true)
in the JSP page without getting to servlet so I can update values without refreshing the page. I've been reading that using ajax with jQuery would be the best way to do that, so can anyone help me of calling the above if statement from jQuery by AJAX.
Try an ajax call to the servlet(not possible without calling servlet) to check whether the function returns true or false then return a flag according to the value(true or false). On that basis you can show an alert or anything else.
For ajax call, you can use:
$.post( "ajax/Servlet_Url", function( data ) { if(data==true) alert("You already Applied"); else window.history.go(-1);});
Refer to following Link for more details about jQuery post request.
https://api.jquery.com/jquery.post/
jQuery(document).ready(function($) {
$("#searchUserId").attr("placeholder", "Max 15 Chars");
$("#searchUserName").attr("placeholder", "Max 100 Chars");
$.ajax({
url:"../../jsp/user/userMaster.do",
data: { drpType : 'userType',lookType : "1" },
success: function (responseJson) {
var myvalue = document.getElementById("userTypeKey");
for(var val in responseJson)
{
valueType = val;
textOptions = responseJson[val];
var option = document.createElement("option");
option.setAttribute("value",valueType);
option.text = textOptions;
myvalue.add(option);
if(valueType == myvalue.value)
{
option.selected = "selected";
}
}
}
});
});
I have a Datatable created, and I'm using jeditable plugin to edit cells to push back data. I can edit the cells but when I hit enter and it sends back to my URL Rest endpoint (which I just have a System.out.println to see the data) I get this error from firebug
"NetworkError: 415 Unsupported Media Type - my rest endpoint url"
My endpoint is expecting an Object in JSON, jeditable is only sending some string parameters. So I need to wrap it up.
Let me post my datatable initialization along with jeditable init.
var computerTable = $("#table_computerTable ").dataTable({
"bProcessing": true,
"bServerSide": true,
"bInfo":false,
"bAutoWidth":false,
"bScrollInfinite":true,
"sAjaxSource": ApiUrl(),
"aoColumns":[ // Maps <th> elements in html to JSON data
{"mData": "id"},
{"mData": "description","sClass" : "read_only"},
{"mData": "serial"},
{"mData": "daily"}
],
"aoColumnDefs":[
{"sName":"id","bVisible":false, "aTargets": [0]},
{"sWidth": "55%","aTargets": [1]},
{"sName":"serial","bVisible":false, "aTargets": [2]},
{"sName":"daily","aTargets":[3]}
],
"fnServerData": function ( sSource, aoData, fnCallback ) {
$.getJSON( sSource, aoData, function (json) {
map = {};
map["aaData"] = json;
fnCallback(map);
});
},
"fnRowCallback": function(nRow, aData, iDisplayIndex ){
$(nRow).attr("id",aData["id"]); // Change row ID attribute to match database row id
return nRow;
}
}).makeEditable({
sUpdateURL: getApiUrl() + "cpu/save",
sReadOnlyCellClass: "read_only",
ajaxoptions:{
dataType: "json",
type: 'POST'
}
});
This is the data I get back when I send the POST (read from firebug)
columnId 3
columnName daily
columnPosition 2
id 24
rowId 0
value 50
What I would like to do is initialize an object and send back all the data I want in that. The ID / Serial / Hourly(the new value)
I don't know enough jquery, javascript to know where to begin with that modification.
Any suggestions?
Edit your makeEditable like this:
makeEditable(
{
sUpdateURL: function(value, settings)
{
var sentObject = {}
var rowId = oTable.fnGetPosition(this)[0];
var columnPosition = oTable.fnGetPosition(this)[1];
var columnId = oTable.fnGetPosition(this)[2];
var sColumnTitle = oTable.fnSettings().aoColumns[columnId].sTitle;
sentObject["rowid"]= rowId
sentObject["columnpos"]= columnPosition
sentObject["columnId"]= columnId
sentObject["sColumnName"]= sColumnTitle
sentObject["valueOfCell"]=value
sentObject["Serial"]="serialnumber"
sentObject["Hourly"]="somevalue"
$.ajax({
type: "POST",
url: "url",
data: "sentObj="+JSON.stringify(sentObject)
})
return value;
},
sSuccessResponse: "IGNORE"
}
);
It's like an own customization of ajax request for updating a cell.