How to get the list in controller through jQuery - java

I have a jsp page , from which I am getting the list of the checkboxes selected by a user.
And as per the selected checkboxes I want to call my controller using the jQuery.
<input type="checkbox" name="XYZ" value="hello1"/>Hello1<br>
<input type="checkbox" name="XYZ" value="hello2"/>Hello2<br>
I obtained all the values in the jQuery and set all the parameters into a variable as given below.
var allVals = [];
$("input[name=XYZ]:checked").each(function() {
allVals.push($(this).val());
});
and I am using an AUI to call my controller, I am passing the value as parameter.
AUI().use('aui-base',
'aui-io-request',
'liferay-portlet-url',
function(A) {
var A = AUI();
var myResourceURL = Liferay.PortletURL.createResourceURL();
myResourceURL.setResourceId('getABC');
myResourceURL.setParameter("action",'ZYX');
myResourceURL.setPortletId(pid);
myResourceURL.setParameter("list",allVals);
A.io.request(myResourceURL.toString(),
{
method : 'post',
dataType : 'text',
on : {
start : function() {
.
.
.});
And in my controller I want to obtain the list and my controller is like this:
System.out.println(request.getParamter("list"));
This statement is just giving me the first selected element, not the complete list of the elements.
Is there something I am missing , or any other way to do it??

I think you will need to go with 'getParameterNames()' instead http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameterNames()
Hope it helps

Related

How to send data from struts2 to a javascript function to draw a chart

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.

populate hidden input form fields based on URLparameters

I have a ppc landing page that I want to change the hidden value of a form field based on the URL parameter.
The field
<input id="Campaign_ID" name="Campaign_ID" type="hidden" value="7g012455dv5441vdf">
The URL would be something like mysite.com/?campaignidvalue=7g012455dv5441vdf
There will be other field "values" that are also based on the URL parameter, so it has to tie the "input id" (or name) to that specific value.
EDIT: There was an error in my code.
PHP would be the easiest!
<?php
if(!empty($_GET['campaignidvalue']))
{
echo '<input id="Campaign_ID" name="Campaign_ID" type="hidden" value="'. $_GET['campaignidvalue'].'"/>';
}
?>
This block will check to see if the value is passed in a GET parameter, and then echo it out into a hidden form field.
The first part:
if(!empty($_GET['campaignidvalue']))
Is checking to see if a parameter named Campaign_ID is being passed.
So your URL of:
mysite.com/?campaignidvalue=7g012455dv5441vdf
Would allow the code to continue, as it is not empty.
This section is the part that actually displays it on the page.
echo '<input id="Campaign_ID" name="Campaign_ID" type="hidden" value="'. $_GET['campaignidvalue'].'"/>';
If you view the source of the HTML page, you would see
By using this function:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null) {
return "";
} else {
return decodeURIComponent(results[1]);
}
}
You'll be able to get any URL parameter by name, like so:
var cid = getParameterByName(campaignidvalue);
Then, once you have the value you can use jQuery to set it, like so:
$(function() {
$("#Campaign_ID").val(cid);
});

How to update session attribute

I have some session attributes being saved. I have a jsp page on which a call to a servlet is made through. This servlet updates one of the session variable but I am not able to see the reflection of these changes in my jsp.Pls help.
In My servlet
List<DriverList> abc = dao.getABC();
request.getSession().removeAttribute("abc");
request.getSession().setAttribute("abc", abc);
In my jsp
function update()
{
var url = "updateServlet";
var req = $.ajax({
type: 'GET',
url: url,
cache: false,
type: "GET",
success: function()
{
latlng = [];
latlng = [<c:forEach var="test" items="${abc}">
[<c:out value="${test.latitude}"/>,<c:out value="${test.longitude}"/>,"<c:out value= "${test.name}" />",<c:out value="${test.cellNo}"/>],
</c:forEach> ];
},
error: function (status) {
}
});
}
The value of ${abc} is same as before. How to get the new value ?
The exact flow -
when login servlet is called abc value as sessionAttribute is set.
Now this redirects to base.jsp. I use abc for the first time. Now after every 30 seconds this update() function is called. This update function calls a servlet through ajax where the session attribute abc is updated.
In the success function of ajax request I want to use this new abc value but getting the old one again.
To access the abc variable in the JSP try:
${sessionScope.abc}
Also note that removing before setting is usually redundant. So:
request.getSession().removeAttribute("abc");
request.getSession().setAttribute("abc", abc);
Can simply become:
request.getSession().setAttribute("abc", abc);
I had similar problem.
It turned out that when you use
HttpSession
object in your controller, it shouldn't be annotated using
#SessionAttributes

Passing name from input to servlet

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

How to create a form with dynamic parameters using javascript?

I am trying to create a form using java script, the form is created but the dynamic param values to the form are not replaced. The following is my form....
var formVar='<form:form name="service_form" commandName="command1" action="/serviceProcess" method="post">';
formVar+='<label for="'+ paramsdata[2] + '">'+paramsdata[3]+'</label><br/>';
formVar+='<form:input type='+paramsdata[2]+' path="webParamMap['+paramsdata[2]+'].webValue" value='+ paramsdata[5] +' class="input"></form:input><br>' ;
formVar+='<label for=" '+paramsdata[2]+' ">'+paramsdata[3]+'</label><br/>';
formVar+='<div id="select">';
formVar+='<form:select path="webParamMap[' +paramsdata[2] + '].webValue">';
formVar+='<form:option value='+paramdata[8]+'>'+paramdata[9]+'</form:option>';
formVar+='</form:select></div>';
formVar+='</form:form>';
In the above form the label tag values(dynamic param values) are updated but the form:input and select tag values(dynamic param values) are not updated in the output.
please help me how to create these tags with dynamic parameters ?
JAVA != JAVASCRIPT
Notice:
<form:form>
This is server-side Java.
Your Javascript is client-side only.
With following script each element is getting its right value. I wonder why are you using "
<script>
var paramsdata = new Array();;
paramsdata[2]='param2';
paramsdata[3]='param3';
paramsdata[5]='param5';
paramsdata[8]='param8';
paramsdata[9]='param9';
var formVar='<form:form name="service_form" commandName="command1" action="/serviceProcess" method="post">';
formVar+='<label for="'+ paramsdata[2] + '">'+paramsdata[3]+'</label><br/>';
formVar+='<form:input type='+paramsdata[2]+' path="webParamMap['+paramsdata[2]+'].webValue" value='+ paramsdata[5] +' class="input"></form:input><br>' ;
formVar+='<label for=" '+paramsdata[2]+' ">'+paramsdata[3]+'</label><br/>';
formVar+='<div id="select">';
formVar+='<form:select path="webParamMap[' +paramsdata[2] + '].webValue">';
formVar+='<form:option value='+paramsdata[8]+'>'+paramsdata[9]+'</form:option>';
formVar+='</form:select></div>';
formVar+='</form:form>';
document.body.innerHTML = formVar;
</script>
<script>
//helper function to create the form
function getNewSubmitForm(){
var submitForm = document.createElement("FORM");
document.body.appendChild(submitForm);
submitForm.method = "POST";
return submitForm;
}
//helper function to add elements to the form
function createNewFormElement(inputForm, elementName, elementValue){
var newElement = document.createElement("<input name='"+elementName+"' type='hidden'>");
inputForm.appendChild(newElement);
newElement.value = elementValue;
return newElement;
}
//function that creates the form, adds some elements
//and then submits it
function createFormAndSubmit(){
var submitForm = getNewSubmitForm();
createNewFormElement(submitForm, "field1", "somevalue");
createNewFormElement(submitForm, "field2", "somevalue");
submitForm.action= "someURL";
submitForm.submit();
}
</script>
<input type="button" value="Click to create form and submit" onclick="createFormAndSubmit()">

Categories