Currently, I have a servlet that forwards to a jsp. The jsp has access to a session attribute "current".
During the loading of the jsp, the information in "current" is passed to a javascript function that generates a graph.
This is all working fine. My only problem is that i'm hard coding the graph data.
How would i go about passing the data array from the servlet to the jsp. Basically, in the creerRapport function, in the 5th argument,
how do I replace that with java attributes?
Any help or ideas would be appreciated.
My current code with hard coded data.
<body onload="soumettreRapport();">
<script type="text/javascript">
function soumettreRapport() {
creerRapport( "${current.title}",
"${current.type}",
${current.width},
${current.height},
[
{
key: "Cumulative Return",
values: [
{
"label" : "2001" ,
"value" : -29.76
} ,
{
"label" : "2002" ,
"value" : 0
} ,
{
"label" : "2003 ,
"value" : 32.80
}
]
}
]
);
return false;
}
In Servlet, You need to to have JSON array as String then put this String into Request scope.
String jsonArrayString = convert(...); // Output [{key:"Cumulative Return", .... }]
request.setAttribute("jsonArrayString", jsonArrayString);
In JSP:
function soumettreRapport() {
var jsonArray = ${jsonArrayString};
creerRapport( "${current.title}",
"${current.type}",
${current.width},
${current.height}, jsonArray );
}
Related
I need to add a dynamic chart into a webapp of mine.
I have choosen chartjs as library (for the line charts)
After the creation of the page with the chart inside and the definition of the action that retrieves data from database I am experiencing some problems sending data from the action to the script that generates the line chart.
The servlet gives as output an ArrayList of Beans
#Action(value="/graphDataFetcher")
public String execute(){
//Connessione a database
DBUtility database= new DBUtility();
Connection connessione=database.getConnected();
listamusei=database.getMusei(connessione);
//Recupero in liste di musei e mostre correlate
for(Museo ms: listamusei){
mostre=new ArrayList<Mostra>();
mostre=database.getMostraInMuseo(String.valueOf(ms.getId()), connessione);
ms.setMostre(mostre);
}
//Disconnessione da database
database.getDisconnected();
return "ok";
}
This is the scripts that "rules" the chart, I want to set the bean's attributes as value1, value2 , value3.. and so on.
<script>
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var lineChartData = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
label: "My First dataset",
fillColor : "rgba(220,220,220,0.2)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,1)",
data : [value1, value2, value3, value4]
},
]
}
window.onload = function(){
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
responsive: true
});
}
</script>
Does someone have some idea about how to fix this?
you can use by two ways
1. take a list in action with setter, getter and add data in this list. In jsp page use strcts tag library and in javascript variable put list data. Then call chartjs library function with data like
<script type="text/javascript">
var a = new Array();
<s:iterator var="newsVar" value="newsList" status="newsStatus">
a[<s:property value="#newsStatus.index"/>]='<s:property value="id"/>';
</s:iterator>
$(document).ready(function(){
chartjsfunction(a);
});
</script>
send ajax call for data to action and send data to chartjs library function.
I have two ajax calls in my jsp code which go to servlet. In first call, I am setting a value in the session and in another call, I am retrieving the same value from the session. Now this value goes as response of the ajax call(2nd ajax call). My problem is:-
This value contains "\n"(eg-("ABC \n def\n geh \n xyz")) . When I store this value in a js variable and try to access it, it takes "\n" as string only. It is not recognising it as newline
ajax calls in jsp:-
$.ajax({
type : "POST",
url : "ConfiguratorStatusReportServlet?method=datagrid",
data : finaldata,
datatype : "JSON",
async : false,
success : function(msg) {
$('#contentDiv').show();
fillDataGrid(msg);
}
});
$.ajax({
type : "POST",
url : "ConfiguratorStatusReportServlet?method=chart",
data : finaldata,
datatype : "JSON",
async : false,
success : function(msg) {
fillDataChartData(msg);
}
});
code in servlet:-
HttpSession session = request.getSession();
String method = request.getParameter("method");
if(method.equalsIgnoreCase("datagrid"))
{
JSONArray listjson = CSR.firstcalledMethod();
String chartformat = CSR.callingMethod2();
System.out.println("chartformat in servlet = "+chartformat);
String result = listjson.toString();
String checkDataExists = (String) (session.getAttribute("chartformat") == null ? "Invalid" : session.getAttribute("chartformat"));
if(!checkDataExists.equalsIgnoreCase("Invalid"))
{
session.removeAttribute("chartformat");
}
session.setAttribute("chartformat", chartformat);
out.write(result);
}
else
{
String chartResult = (String) session.getAttribute("chartformat");
session.removeAttribute("chartformat");
out.write(chartResult);
}
now in the same jsp which contains the ajax calls shown above I am trying to access the variable as :-
function fillDataChartData(dataVAR) {
var chartdata = dataVAR;
alert("chartdata = "+chartdata);
}
Suppose the response in ajax contains data "APAC-OTHER,0.05 \n FCS,99.95"(i.e. dataVAR = "ABC \n DEF \n GHI" ). Now, when I am trying to alert it in the function fillDataChartData(dataVAR), it shows "APAC-OTHER,0.05 \n FCS,99.95" in alert but I want it like APAC-OTHER,0.05
FCS,99.95
How should I do that?? Please help...
It's strange. May be there are some hidden chars in your response? Anyway, you can try to replace linebreaks by br tags:
function fillDataChartData(dataVAR) {
var chartdata = dataVAR.replace(/\\n/gm, '<br>');
alert("chartdata = "+chartdata);
}
I have an input:
Now this is one input from a div with several different inputs, there is a button called add exp which generates a new div with those inputs by calling href="#" and then jquery does the rest, only the name changes to for example institutionName0, institutionName1 etc so the fields get distinct. In my servlet I want to be able to get the actual input name like institutionName0 so I can check how much of the same fields are generated and that I can put in different values in those different fields.
You can send your form values to Servlet as a jSon object using ajax.
//Example
function onSubmit(divName){
document.forms["formName"]["formName_currentAction"].value = divName;
var theForm = $("form[name=formName]");
var params = theForm.serialize();
$.ajax({
type:"POST",
url:actionURL,
cache: false,
data:params,
success:function(data, textStatus, XMLHttpRequest){
//do something here
},
error:function(XMLHttpRequest, textStatus, errorThrown){
}
});
I have a file called wfd.proxy.js that contains the following lines of code :
if (!WFD) { var WFD = {}; };
if (!WFD.Proxy) { WFD.Proxy = {}; };
WFD.Proxy =
{
SERVICE_URL : "/delegate/WFD/WFService?",
PDF_SERVICE_URL : "/delegate/pdf-exporter?",
DATA_TYPE : "json", // used by jQuery
DATA_TYPE_EXT : "ajax", // used by ExtJs
DATA_TYPE_TXT : "text", // used for tests
SaveWorkflow : function(code)
{
jQuery.ajax({
url: WFD.Proxy.SERVICE_URL + "task=savemodel",
data: { code : code },
dataType : WFD.Proxy.DATA_TYPE,
type: 'POST',
success : function(data) {
WFD.Proxy.OnSaveWorkflowCallback(data);
},
error : function(jqXHR, textStatus, errorThrown) {
alert("Errore di comunicazione: " + errorThrown);
}
});
}
,
WFD.Proxy.OnSaveWorkflowCallback = function(data)
{
/*
data.response
data.message
data.model_new_id
data.idsNodes[i].original_id
data.idsNodes[i].new_id
*/
}
};
I have written the code that converts an xml file to JSON format. The JSON string that i get from the code I've written until now, should be passed as the code parameter of SaveWorkflow : function(code) .
I'm not really sure what do I have to do at this point.
I did some searches and saw that jQuery.ajax() calls where manipulated using Java Servlets ...
Any idea how to resolve this please?
Thanks in advance
What you've written is client side code (i.e. executes in your browser). The part that's missing is the server side. Your "ajax call" is making an asynchronous connection to a web server, using this URL:
/delegate/WFD/WFService?task=savemodel&code=xxxx
xxxx is the value of the code variable. Your javascript is expecting a text string as response from this URL.
You don't need a servlet per se to handle this. Any web server that accepts the ajax URL and returns the required data will do (e.g. PHP...)
If you need a servlet and you don't know how to build one, I think you have a lot of reading to do.
I suggest:
https://www.google.be/search?q=my+first+servlet
var schedule = [];
var data = {
'user_id' : '12',
'day_of_week' : 'Monday',
'when' : 'start',
'modified' : 'true'
}
schedule.push(data);
var data = {
'user_id' : '13',
'day_of_week' : 'Tuesday',
'when' : 'end',
'modified' : 'false'
}
schedule.push(data);
// schedule would have two objects in it
I am posting array to servlet using jquery ajax post request as below .
data : {'myData':schedule},
url :"./myController",
Now how can I get array of objects and literate to get all the values? Each array object has string, long and boolean type values. How can I get all the values by iterating?
May be you can try this
json.getJSONObject("myData").getString("your_values");