Render List returned via JQuery - java

On the server side, I have a list into a bean.
On the Client side, I use:
function callJava() {
$.getJSON("../reference/test", { name: $('#name').val()}, function(result) {
// result is a bean that has a list
alert(result.fooList.length);
});
}
I need to be able to render this list later via FreeMarker.
What is killing me when I replaced this list with a String variable, it works fine like:
function callJava() {
$.getJSON("../reference/test", { name: $('#name').val()}, function(result) {
alert(result.stringVariable)
});
}
How could I deal with the string into that bean !!

If all you want to do is manipulate the elements of the list:
function callJava() {
$.getJSON("../reference/test", { name: $('#name').val()}, function(result) {
for (var i = 0; i < result.fooList.length; ++i)
alert(result.fooList[i]);
});
}

Actually I have just an update over my question is that the list I'm trying to return from the server side is a SCALA list . I have solved this issue by using an array instead of JAVA . and it works fine by using the following as Pointy said :
function callJava() {
$.getJSON("../reference/test", { name: $('#name').val()}, function(result) {
for (var i = 0; i < result.fooList.length; ++i)
alert(result.fooList[i]);
});
}

Could you capture the JSON response and post it? The jQuery getJSON method will silently swallow any parsing errors from malformed JSON. That is probably what happened.

Related

How to store this incoming data from back end to an array object of type periodic element

I am new to angular and I have a requirement where I need to perform some operations to the incoming data and then show it in a table.
my current code fetches data from back end and shows it in a table.
But, what I need is to first store incoming data in a array object and then perform some operations (if else conditions and basic calculations)and then show it in the table.
export interface PeriodicElement {
"date":'',
"endDate":'',
"groupa":'',
"hoA":'',
"hoB":'',
"hoC":'',
"mCommission":''
}
const ELEMENT_DATA: PeriodicElement[] = [];
#Component({
selector: 'kt-dynamic-table',
templateUrl: './dynamic-table.component.html',
styleUrls: ['dynamic-table.component.scss'],
})
export class DynamicTableComponent implements OnInit , PipeTransform {
tableData : any;
displayedColumns: string[] = ['date', 'endDate', 'groupa',
'hoA','hoB','mCommission','action'];
dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);
myTable:any;
inputData:any;
loggedData : any;
index : number;
updateStatus : boolean = false;
#ViewChild(MatSort, { static: true }) sort: MatSort;
constructor( private apiService:ApiService ,private cdRef: ChangeDetectorRef) {
}
ngOnInit(): void {
console.log('Dynamic Table');
this.inputData = {
"date":'',
"endDate":'',
"groupa":'',
"hoA":'',
"hoB":'',
"hoC":'',
"mCommission":'',
};
this.myTable = [];
this.loggedData = JSON.parse(localStorage.getItem("loggedData"));
console.log(this.loggedData.id);
this.getTableData();
this.cdRef.detectChanges();
}
getTableData(){
let url = 'http://test1-env.jkbp6sft6f.ap-south-1.elasticbeanstalk.com/api/maMaster';
this.apiService.GET(url).subscribe((resp: any) => {
this.tableData = resp.body;
this.updateTable(this.tableData);
console.log(this.tableData);
this.cdRef.detectChanges();
}, err => {
console.log(err);
});
}
What I am expecting is to get data from back end in array object.
like:
PeriodicElement[] = incoming data
then perform operations then show it in a datatable.
Your interface properties should have proper typing instead of ''
export interface PeriodicElement {
date:string,
endDate:string,
groupa:string,
hoA:string,
hoB:string,
hoC:string,
mCommission:string
}
then change your get call to
this.apiService.GET(url).subscribe((resp: any) => {
let data:PeriodicElement[] =resp.body;
//here perform some opration with data eg. data.map etc.
this.tableData = data;
this.updateTable(data);
this.cdRef.detectChanges();
}, err => {
console.log(err);
});
You could do something like this:
export interface PeriodicElement {
date:string,
endDate:string,
groupa:string,
hoA:string,
hoB:string,
hoC:string,
mCommission:string
}
And then, in your get you can specify your specific type:
this.http.get<PeriodicElement >(url).subscribe(response =>{
let data:PeriodicElement[] = response ;
});
This way you can directly map response without using pipe filters or map operators.
Bingo!!,
You can use .map function provided by RxJs
this.http.get<PeriodicElement >(url).subscribe(response =>{
let data:PeriodicElement[] = response ;
});
just write this code like:
.map(response =>{
// your working logic should go here now. This the standared way to deal with the
responses
}).subscribe(response =>{
let data:PeriodicElement[] = response ;
});

java spring boot pass array of strings as parameters inside json for ajax call

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

calling a Java method by AJAX

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";
}
}
}
});
});

How to render a List in playframework

i am wondering how i can render a List to template as an ajax callback arg.
i did this:
List<String> filteredTW = Twitt.filtertw(tagname);
return ok(filteredTW).as("text/plain");
but is says, i need to define ok(List) function on my own. is it true that Playframework doesnot offer this function?
i would be thanksful to any attemp to help..
EDIT: my ajax function is:
$(function() {
$('.filter').click(function() {
var tagname = $(this).text();
$('.post').remove();
$.ajax({
url: '/filter',
type: 'POST',
dataType: 'html',
context: this,
data: { tags: tagname },
}).success(function(response) {
alert(response);
});
});
})
thanks
You might want to try return ok(play.libs.Json.toJson(filteredTW));
In this case, you can treat response as a regular javascript array.
for (i = 0; i < response.length; i++)
alert(response[i]);

Using jQuery, how do I way attach a string array as a http parameter to a http request?

I have a spring controller with a request mapping as follows
#RequestMapping("/downloadSelected")
public void downloadSelected(#RequestParam String[] ids) {
// retrieve the file and write it to the http response outputstream
}
I have an html table of objects which for every row has a checkbox with the id of the object as the value. When they submit, I have a jQuery callback to serialize all ids. I want to stick those ids into an http request parameter called, "ids" so that I can grab them easily.
I figured I could do the following
var ids = $("#downloadall").serializeArray();
Then I would need to take each of the ids and add them to a request param called ids. But is there a "standard" way to do this? Like using jQuery?
I don't know about "standard way", but this is how I would do it.
var ids = $("#downloadall").serializeArray();
will give you a dataset on the form (only the checked items presented):
[{name:"foo1", value:"bar1"}, {name:"foo2", value:"bar2"}]
To feed this to jQuery's .ajax() just:
$.ajax({
url: <your url>,
data: ids.map(function (i) {return i.name+'='+i.value;}).join('&')
});
The Array.map() is not compatible with all browsers yet so you better have this code on your page too:
if (!Array.prototype.map) {
Array.prototype.map = function(fun /*, thisp*/) {
var len = this.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this)
res[i] = fun.call(thisp, this[i], i, this);
}
return res;
};
}
This code snippet I got from mozilla developer center.
I didn't put them in a ?ids=... param, but this way they are easy to access on server side. You can always just modify the map function to fit your needs.

Categories

Resources