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);
}
});
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 trying to upload csv into my mysql db using jooq how ever i am getting following error.I tried various solutions suggested on net but cant fix it
Error: org.jooq.exception.DataAccessException: SQL [insert into `Test`.`testtable` <mydata> Incorrect string value: '\xEF\xBF\xBD15 ...' for column 'colum_Name' at row 1
How I am uploading csv to jooq
create.loadInto(Tables.TableName)
.onErrorIgnore()
.loadCSV(new File("/tmp/uploaded-files/" + fileName), "UTF-8").<fields>.execute();
I ensure file is in utf-8 however when ever there is UTF-8 character record is failing to save in DB and throwing above error.I ensured using
file -i <filename>
front end ajax:
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: fileUploadUrl,
data: dataforFileUpload,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (message) {
console.log(message);
alert(message);
console.log("upload done "+ new Date());
},
error: function (e) {
console.log("ERROR : ", e.responseText);
alert("ERROR : "+ e.responseText);
}
});
I am getting file from my front end reading it via java rest
InputStream inputStream = listingFilePart.getBody(InputStream.class, null);
and writing file recursively in local system before passing to jooq
PrintWriter fop = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file, true), StandardCharsets.UTF_8));
I set my DB to accept utf-8 and I verified the same
I found the issue.Issue is on ajax call.
I need to send charset with enctype like
$.ajax({
type: "POST",
enctype: 'multipart/form-data;charset=UTF-8',
url: fileUploadUrl,
data: dataforFileUpload,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (message) {
console.log(message);
alert(message);
console.log("upload done "+ new Date());
},
error: function (e) {
console.log("ERROR : ", e.responseText);
alert("ERROR : "+ e.responseText);
}
});
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),
I am doing Java Chat application .
I will call the pingAction() in my external Jquery when my application get initiated.
I used this site for reference of long polling with JQUERY - http://techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and-jquery
The Jquery pingAction will be ,
function pingAction(){
$.ajax(
{
type: "post",
url: "PingAction",
async: false,
data : "userId="+encodeURIComponent(userId)+"&secureKey="+encodeURIComponent(secureKey)+"&sid="+Math.random() ,
cache:false,
complete: pingAction,
timeout: 5000 ,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
scriptCharset: "utf-8" ,
dataType: "html",
error: function (xhr, ajaxOptions, thrownError) {
alert("xhr.status : "+xhr.status);
if(xhr.status == 12029 || xhr.status == 0){
//alert("XMLHttp status : "+xhr.status);
$("#serverMsg").css("backgroundColor" , "yellow");
$("#serverMsg").text("Your Network connection is failed !");
$("#serverMsg").show();
}
//setTimeout('pingAction()', 5000);
xhr.abort();
},
success: function( responseData , status){
if($("#serverMsg").text() == "" || $("#serverMsg").text() == "Your Network connection is failed !"){
disableServerMessage();
}
if(responseData != "null" && responseData.length != 0 && responseData != null){
var stringToArray = new Array;
stringToArray = responseData.split("<//br//>");
var len = stringToArray.length;
for(var i=0;i<len-1;i++){
getText(stringToArray[i]);
}
}
//setTimeout('pingAction()', 5000);
}
}
);
}
Before using the Long Poling , I will call the pingAction() in javaScript for every 5 seconds using the setTimeInterval().
Now I need to use the LONG POLLING concept in the Chat application (Wait until the server gives the new messages).So I modified my Jquery pinAction() what you have seeing above.
Is there any built in method to do the Long polling in JQUERY ?
No, there is no built in method in jQuery to do long polling. You will have to either develop your own or find existing code that solves your problem.
If you're looking for ideas, you can start with a Google search for "long polling in jQuery". There are plenty of examples to learn from.