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),
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"
}
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.
I am doing an ajax call to the java servlet. The servlet responds with a JSON Array with a charset set to UTF-8. However, once I get a response in the AJAX call, I get ??? characters in my strings. I went through a lot of testing and research and could not find a possible solution.
AJAX CALL:
$.ajax({
type: 'POST',
data: {curTableName: curTableName,curTableID: curTableID},
dataType: 'json',
url: '../ShowProducts',
success: function(productInfo){
var noOfProducts = productInfo.length;
for(var i = 0; i < noOfProducts; i++)
{
product.push(productInfo[i].product.substr(0,25) + "...");
webshop.push(productInfo[i].webshop);
price.push(productInfo[i].price);
availability.push(productInfo[i].availability);
lastChecked.push(productInfo[i].lastChecked);
checkFreq.push(productInfo[i].checkFreq);
url.push(productInfo[i].url);
DisplayProductInfo(product[i],webshop[i],price[i],availability[i],lastChecked[i],checkFreq[i],url[i]);
}
}
});
And my Java Servlet Response:
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonArr.toString());
Based on my own research the java servlet seems to be correct, and maybe there is an issue with the javascript. Anybody has any good ideas. All help is greatly appreciated. :)
I have managed to get it work. The problem resided in the fact that the JSON needed to be encoded in the servlet, and decoded in the javascript. Thank you - isah.
CODE CHANGES:
AJAX CALL:
$.ajax({
type: 'POST',
data: {curTableName: curTableName,curTableID: curTableID},
dataType: 'json',
url: '../ShowProducts',
success: function(productInfo){
var noOfProducts = productInfo.length;
for(var i = 0; i < noOfProducts; i++)
{
productInfo[i].product = decodeURIComponent(productInfo[i].product);
productInfo[i].product = productInfo[i].product.replace(/\+/g, ' ');
product.push(productInfo[i].product.substr(0,25) + "...");
webshop.push(productInfo[i].webshop);
price.push(productInfo[i].price);
availability.push(productInfo[i].availability);
lastChecked.push(productInfo[i].lastChecked);
checkFreq.push(productInfo[i].checkFreq);
url.push(productInfo[i].url);
DisplayProductInfo(product[i],webshop[i],price[i],availability[i],lastChecked[i],checkFreq[i],url[i]);
}
}
});
JAVA SERVLET:
productSplit[0] = URLEncoder.encode( productSplit[0], "UTF-8");
Additional line has been added to Java servlet. Now the title gets encoded, and only after that it goes to the JSON object.
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 am trying to retrieve issues in a JIRA plugin using the REST API, but when I supply authentication information, it logs me in as that user afterwards. I would like to retrieve an issue without having to change users. Here is my AJAX:
jQuery.ajax({
type: "GET",
url: "http://jdev.tmaxlaunch.com/rest/api/2/search?jql=cf[10201]=" + id,
//headers: { 'Authorization': 'Basic xxxxxxxxx' },
dataType: "json",
success: function(data) {
console.log(data);
//console.log(data.issues);
//console.log(data.issues[0]);
for (i = 0; i < data.issues.length; i++){
console.log(data.issues[i].id);
AJS.$('.activity-chart').append('<p>' + data.issues[i].fields.summary + '</p>');
}
},
error: function(xhr,textStatus,err)
{
console.log("readyState: " + xhr.readyState);
console.log("responseText: "+ xhr.responseText);
console.log("status: " + xhr.status);
console.log("text status: " + textStatus);
console.log("error: " + err);
}
});