Passing name from input to servlet - java

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

Related

Ajax call returns string for Highcharts series but result is wrong (parsing error?)

I'm developing a Java Spring-Hibernate application that uses Highcharts. I've got a JavaScript function that, when called, it makes an Ajax call to get the chart data (series) and creates the chart with it:
<!-- Stacked bar chart -->
<script type="text/javascript">
//Function that plots the highcharts chart
function plot(park) {
$.ajax({
type: "get",
url: "MainView/report/datagaps/" + park,
dataType: "text",
error: function (error) {
console.log(error);
alert('Error while requesting datagaps for ' + park + ' : ' + error);
},
success: function (result) {
$("#chart" + park).highcharts({
chart: {
type: 'column'
},
series: result
});
}
});
}//END_FUNCTION
</script>
I've removed most of the plot options code, so you see the most relevant code above. There is a model method that deals with this request:
#RequestMapping(value = "/datagaps/{parkName}", method = RequestMethod.GET)
public #ResponseBody String datagaps(#PathVariable String parkName, Map model, HttpSession session) {
LOGGER.debug("Successfully called datagaps for '" + parkName + "'");
LOGGER.debug((String) session.getAttribute("chartData"+parkName));
return (String) session.getAttribute("chartData"+parkName);
}//END_METHOD
The method is quite simple: a session string variable is returned, which is the one that should be used in series: result.
The thing is that this generates an unexpected result:
However, if I set a model variable session.setAttribute("chartData" + park, rrdao.getParkData().get(park)); before loading the form and I use it instead of the result like series: ${chartDataAA}, it works:
This is quite weird, since the data used is exactly the same: both ajax call and model variable come from the same place, and they are logged before beign send, which allows me to be sure data is good. This data has a format like [{name:'AA01', data: [[1412114400000,0],[1412200800000,0],[1412287200000,0],[1412373600000,0],[1412460000000,0],[1412546400000,0],[1412632800000,0]}]
I bet is some kind of string parsing problem when it is returned from the ajax call, perhaps due to the single quotations, but I don't know how to deal with it.
Please help!
Maybe it is misspelling, but your single serie which you have as missing bracket in data array. It should be: [{name:'AA01', data: [[1412114400000,0],[1412200800000,0],[1412287200000,0],[1412373600000,0],[141246‌​0000000,0],[1412546400000,0],[1412632800000,0]] }]
Change: dataType: "text" to dataType: "json"
Then in the controller if you use jackson json just return a List

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

Jquery autocomplete issue

I am new to jQuery and am trying to use the autocomplete widget with an ajax call to my database.
I am able to call the database, returned ArrayList of string values, and converted the response as a JSON object using org.codehaus.jackson.map.ObjectMapper (Do I need to use something else?).
When I put an altar, I can see results as pure strings with comma delimiter, but am not able to see a suggestion list with autocomplete.
Java code that returns the JSON object using org.codehaus.jackson.map.ObjectMapper:
response.setContentType("application/json");
response.setHeader("cache-control", "no-cache");
ArrayList polNo = doa.getPolicyData(ajaxForm.getPolicyNumber());
ObjectMapper mapper = new ObjectMapper();
OutputStream out = response.getOutputStream();
mapper.writeValue(out, polNo);
JavaScript code:
$( "#policyNumber" ).autocomplete({
source: function (request,response){
$.ajax({
type: "POST",
url: "/NB/AjaxSubmit.do",
dataType: "json",
data: {policyNumber: request.term},
success: function (data) {
alert(data);
}
});
},minLength: 3
});
alert data showing as : TMA412732,TMA412733,TMA412734
In above code, I have returned ArrayList of string values and was able to show in autopopulate. I have enhanced the above code to return list of person objects that has first name, last name etc. Now when user typing the firname or last name in the autopopulate , I would like to suggest First name, LastName Middle.
Could someone help to enhance this? Thanks!
success: function(data) {
response(data);//u forgot to set data on response
}
Change success function like
success: function (data) {
response(data); //u forgot to set data on response
}

Passing selected check boxes using jQuery servlet [duplicate]

This question already has answers here:
How to send request parameter array to servlet using jQuery $.ajax?
(4 answers)
Closed 6 years ago.
How can I pass selected checkbox values to another servlet (not below one) using jQuery post method?
This is my servlet code for generationg check boxes on the html page I am using json
for(int i=0;i<roles.size();i++){
JSONObject msg = new JSONObject();
msg.put("selector", "#roles");
//<input type=radio name="radio" value="<%=bean.getSno()%>"></td>
msg.put("msg",
"<input type=checkbox id="+'"'+"checkedroles"+'"'+"name="+'"'+"checkedroles"+'"'
+"value="+roles.get(i)+">"+roles.get(i)+"<br>");
messages.put(msg);
}
this is the jquercode
*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
$(document).ready(function(){
//global vars
var UserName = $("#UserName"); //user name field
var FirstName = $("#FirstName"); //first name
var LastName=$("#LastName");
var StreetAdress=$("#StreetAdress");
var City=$("#City");
var Province=$("#Province");
var Organization=$("#Organization");
var email=$("#email");
var phone=$("phone");
var checkedroles=$("#checkedroles");
var selected = new Array();
function checkCommentsForm(){
return true;
}
$("input:checkbox[name=checkedroles]:checked").each(function() {
selected.push($(this).val());
});
//When form submitted
$("#Reg").submit(function(){
if(checkCommentsForm()){
$.ajax({
type: "post",
url: "loginProcess.jsp",
data: {user : UserName.val(), fname : FirstName.val(),lname : LastName.val()
,stAddress:StreetAdress.val(),city:City.val(),prov:Province.val(),org:Organization.val()
,mail:email.val(),ph:phone.val(),'ch[]':selected},
success: function(data) {
}
});
}
});
});
also pls tell me how to retrieve the array in the servlet
You haven't shown your HTML but from the looks of it, it seems like these values are in a form.
You could then use ('#Reg').serialize() instead. This will Encode a set of form elements as a string for submission. - it will include all successful controls so all checked checkboxes will be included automatically as will all enabled text fields.
$("#Reg").submit(function(){
if(checkCommentsForm()){
$.ajax({
type: "post",
url: "loginProcess.jsp",
data: $(this).serialize(),
success: function(data) {
}
});
}
});
To retrieve the submitted values in your servlet, use the ServletRequest#getParameter() and ServletRequest#getParameterValues() methods. The former for when you have just one value for a parameter (for example, a test field) and the latter when you can have multiple values with that parameter name, for example, multiple checkboxes with the same name as is the case in your question. So you'd write something like this in your servlet:
String [] checked = request.getParameterValues("checkboxname");

Struts2 JQuery how to do onchange ajax

Let's say I have sj:autocompleter like this :
<sj:autocompleter id="idDistributor"
name="idDistributor"
list="%{idDistributorList}" label="ID
Distributor" indicator="indicator" />
when the value is changed, I'd like to pass the detail value to other text field like this :
<sj:textfield label="Nama Distributor" id="namaDistributor" name="namaDistributor" required="true"/>
where its value will be retrieved from struts back bean (FormAction).
How I could do this?
Really thanks in advance.
Mr.K
The following will send the autocompleter value to your action and set the value of #namaDistributor with the returned string:
$('#idDistributor').change(function(){
// Make the ajax request
$.ajax({
url: 'path/to/back-bean.action',
data: "autocompleterValue=" + $(this).val(),
dataType: "json",
success: function(data) {
// Set the inputs from the json object
$('#namaDistributor').val(data.distributor);
$('#namaPrice').val(data.price);
}
});
});
You can read more about the $.ajax() method here. The above json example assumes that your Action is creating a json object with the following format:
{"price": "123.40", "distributor": "XYZ Inc."}
You can read more about using json with Struts2 in this article.
you can do this with onSelectTopics.
Subscribe a topic like this:
<script>
$.subscribe('autocompleteSelect', function(event, data) {
var ui = event.originalEvent.ui;
$('#namaDistributor').val(ui.item.value);
});
</script>
and at it to your autocompleter
<sj:autocompleter id="idDistributor"
name="idDistributor" onSelectTopics="autocompleteSelect"
list="%{idDistributorList}" label="ID
Distributor" indicator="indicator" />
you can find an example for this in the Struts2 jQuery Plugin Showcase

Categories