how to get object using callback data in jquery? - java

i am using jquery to get values from database via servlet. callback function in my script gives me raw information from database.how can i append these values to select option in jsp.
here is my Retrive_country servlet code:
String sql1 = "SELECT * FROM state WHERE country_ref="+countryref+"
PreparedStatement pst1 = db.getConnection().prepareStatement(sql1);
ResultSet j = pst1.executeQuery();
while (j.next()) {
state_id = j.getString(1);
state = j.getString(2);
country_ref = j.getString(3);
location.setState(state);
location.setState_id(state_id);
location.setcountry_ref(country_ref);
pw.println(state_id);
pw.println(state);
pw.println(country_ref);
}
here is my script:
<script>
$(document).ready(function(){
$("#country_id").change(function() {
var xyz = $("option:selected").val();
alert(xyz)
$.get("../Retrive_country?countryREF="+xyz",
{countryREF : xyz },
function(data){
console.log(data);
alert("Data: " + data);
});
});
});
</script>
here is my jsp:
<div class="span2 clear">
<select name="country_id" id="country_id">
<option>-select-</option>
<option id="blabbb">1</option>
<option id="blabbb">2</option>
<option id="blabbb">3</option>
</select></div>
<div class="span2 clear">
<select name="state_ref" id="state_ref">
<option ></option>
</select></div>
here is my output in console:
all the strings are state values and integers are stateid.
i want them to be used separately in jsp.

You should better use a backend JSON encoder. But this manual encode should work, too:
Backend code:
pw.println("[");
while (j.next()) {
state_id = j.getString(1);
state = j.getString(2);
country_ref = j.getString(3);
pw.println("{stateId: " + state_id + ", stateName: \"" + state +"\"},");
}
pw.println("]");
(I'm assuming your state_id is integer)
Client code:
$("#country_id").change(function() {
var xyz = $("option:selected").val();
$.get("../Retrive_country?stateadd_1=none", {countryREF : xyz }, function(data){
var states = eval(data);
$('#state_ref').empty();
$.each(states, function(index, state){
$("<option></option>")
.attr("value", state.stateId).text(state.stateName)
.appendTo('#state_ref');
});
}, 'text');
});
Cheers, from La Paz, Bolivia

Assuming you can send data as json. You can do this:
var Myselect = $('#state_ref');
$.getJSON("../Retrive_country?stateadd_1=none",
{countryREF : xyz } ,function(data){
$.each(data, function(key, value) {
Myselect
.append($("<option></option>")
.attr("value",key)
.text(value));
});//end each
});//end get
If not in json format, can you show what your data looks like?

DO NOT USE + in the PreparedStatement query!!
It's intended for using things like
String sql1 = "SELECT * FROM state WHERE country_ref=?"
PreparedStatement pst1 = db.getConnection().prepareStatement(sql1)
pst1.setInteger(0,country_ref);
ResultSet j = pst1.executeQuery();
It is because of SQL injection. As described, the easiest way to escape that injection type is using prepared statements properly. Please read more about using PreparedStatement

Related

If else not working on the basis of user selection

I am working on HTML tables. For that I am returning JSON from my Java code. I have a UI as HTML page where there is a form having from date to date and a select tag having 4 options like this
<form id="formId" method="get">
<div class="container">
<h4>Start Date:</h4>
<input type="text" id="startdate" name="fromdate" width="276"
placeholder="dd/mm/yyyy" required />
<h4>End Date:</h4>
<input type="text" id="enddate" name="todate" width="276"
placeholder="dd/mm/yyyy" required />
<h4>Outlets:</h4>
<select name="outlet" id="all">
<option>ALL</option>
<c:forEach var="item" items="${obj.outlet}">
<option>${item}</option>
</c:forEach>
</select>
<br>
<br>
<div>
<button id="button" class="btn btn-default" type="submit">Search</button>
</div>
</div>
</form>
I am taking that input from the form and getting values in the servlet in doget method like below:
String fromdate=request.getParameter("fromdate");
String todate=request.getParameter("todate");
String outlet=request.getParameter("outlet");
// System.out.println(String.format("fromdate: %s, todate: %s, outlet: %s", new Object[]{fromdate, todate, outlet}));
List<String> outletList = Arrays.asList(outlet.split("\\s*,\\s*"));
try {
String json = HourlySalesDateOutlet.createJson(outletList, fromdate, todate);
response.getWriter().write(json);
// System.out.println("dheeraj"+json);
}
catch (Exception e) {
e.printStackTrace();
}
}
Now here is my Java class where I have written two queries one for if the user selects all and other if user select specific outlet. My problem is the if statement is not executing only else is executing if the user selects one outlet from FORM if the user selects ALL then it's not working.
Below is my code:
public static String createJson(List<String> outletList, String startDate, String endDate) throws Exception {
Connection con = null;
String query1;
List<Map<String, String>> mapList = new LinkedList<Map<String, String>>();
String outletStr = outletList.stream().collect(Collectors.joining("','", "('", "')"));
if (outletList.equals("ALL")) {
query1 = "SELECT a.OUTLET,b.CUSTOMERDESCRIPTOR,a.BILLDATE,HOUR(a.BILLTIME) AS HOURS, SUM(a.NETAMOUNT) AS AMOUNT FROM SYNCBILL a,ecustomer b WHERE a.OUTLET=b.CUSTOMERIDENTIFIER AND a.CANCELLED<>'Y' AND a.BILLDATE BETWEEN STR_TO_DATE(REPLACE('"
+ startDate + "','/','.'),GET_FORMAT(DATE,'EUR')) AND STR_TO_DATE(REPLACE('" + endDate
+ "','/','.'),GET_FORMAT(DATE,'EUR')) GROUP BY OUTLET,BILLDATE,HOUR(BILLTIME)";
System.out.println("all"+query1);
} else {
query1 = "SELECT a.OUTLET,b.CUSTOMERDESCRIPTOR,a.BILLDATE,HOUR(a.BILLTIME) AS HOURS, SUM(a.NETAMOUNT) AS AMOUNT FROM SYNCBILL a,ecustomer b WHERE a.OUTLET=b.CUSTOMERIDENTIFIER AND b.CUSTOMERDESCRIPTOR in "
+ outletStr + " AND a.CANCELLED<>'Y' AND a.BILLDATE BETWEEN STR_TO_DATE(REPLACE('" + startDate
+ "','/','.'),GET_FORMAT(DATE,'EUR')) AND STR_TO_DATE(REPLACE('" + endDate
+ "','/','.'),GET_FORMAT(DATE,'EUR')) GROUP BY OUTLET,BILLDATE,HOUR(BILLTIME)";
System.out.println("2"+query1);
}
try {
con = DBConnection.createConnection();
PreparedStatement ps = con.prepareStatement(query1);
ResultSet rs = ps.executeQuery();
Map<RecordKey, Long> mapData = getMapList(rs);
}
I am not posting the full Java code. What I want is if the user selects all then if statement should execute and the query in it should execute. If the user selects else, then other should work, and here in my code only else is working if is not executing.
How can I debug this?
I have a simple solution for your problem. When user selects all, then in that case pass the empty list and while making the query just put this condition.
if (outletList.size()==0) {
// case for all
} else {
// do regular stuff
}
As pointed out in the comments, you're not comparing comparable types. outletList is a List and it can't be equated to a String even though the list may only contain a single element that happens to be a String. So, outletList.equals("ALL") doesn't do what you think it does.
But that raises an interesting point. You have a select list which isn't multiple so why return a list of what is always a single value? And why switch to sending back an empty list when ALL is selected? That doesn't make sense; there was a single selection made as expected. This adds unnecessary confusion.
Try instead sending back the single value as a String and letting that value determine the logic so you have flexibility. If it's not possible to avoid the list then accept only a single value (list[0] for example) and call equals on that not the List.
if(outletList[0].equals("All")) {...}
If you later find yourself in a situation where you need more than a single if-else pair, you can switch to a switch like so:
switch(outletList[0]) { // or the single value...
case "ALL":
...
...
default:
...
}

create two values in drop down list using data passed through JSON and jQuery

I am passing HashMap using jQuery and JSON to JSP page. The values being returned to jQuery success function are as follows:
Formatted JSON Data
{
"tableBird1":[
"001",
"Eurasian Collared-Dove"
],
"tableBird2":[
"002",
"Bald Eagle"
],
"tableBird3":[
"003",
"Cooper's Hawk"
]
}
I want to to populate a dropdown list based on these values where a dropdown contains two values.
Here is the code I am trying:
$.ajax({
type:"GET",
url: "url?",
data: { groupName: $('#groupNamesDD').val() }, // Data being passed through json from other drop down list
dataType: "json",
success: function(response){
$.each(JSON.stringify(response), function(key,value) { // I get this exception here - Cannot use 'in' operator to search for '294' in
var element = document.createElement("option");
for(var i = 0; i < key.length; i++) {
element.value= JSON.stringify(key);
element.data-value = JSON.stringify(key.value); // here I get run time exception - invalid left hand assignment
element.text=JSON.stringify(key.value);
document.getElementById("displayColumnsDropDown").add(element);
}
});
}
});
I want the output something like this:
<select id="displayColumnsDropDown" >
<option value="">-- Select --</option>
<option value="tableBird1" data-value="001" >001</option>
<option value="tableBird1" data-value="Eurasian Collared-Dove" >Eurasian Collared-Dove</option>
<option value="tableBird2" data-value="002" >002</option>
<option value="tableBird2" data-value="Bald Eagle" >Bald Eagle</option>
<option value="tableBird3" data-value="003" >003</option>
<option value="tableBird3" data-value="Cooper's Hawk" >Cooper's Hawk</option>
</select>
I got the possible solution form this link Can an Option in a Select tag carry multiple values?
I don't know how to create more than one values for drop down list dynamically other than this way. Is there any other possible solution?
EDIT 1:
Tried the following code:
$('#displayColumnsDropDown').append($('<option>', { value: key }).data-value(key.value).text(key.value));
In the second for loop of success method. I still get the same exception:
Cannot use 'in' operator to search for '805' in
I am answering my own question . It might help someone
var $select = $('#displayColumnsDropDown');
$.each(response,function(key,value)
{
if(value instanceof Array)
{
for(var i=0;i<value.length;i++)
{
$select.append('<option value=' + key + ' data-value= ' +value[i]+ '>' + value[i] + '</option>');
}
}
});
Syntax of my HashMap what I am passing to through JSON is something like this:
Map<String, List<String>> listOfColumns =new HashMap<String, List<String>>();
List is treated as Javascript Array which is taken as value in my jQuery loop.
Also I need not parse value ( which is response variable in my case )returned in success function because it is already being parsed for me.
The reason for my exception was I was parsing it again.
Thanks to all the previous answers on Stack Overflow.

How can I filter the result given by c:forEach using the value selected in a drop down?

Following is my jsp code.
<c:forEach items="${nameList}" var="studentList">
<tr>
<td style="padding-bottom: .5em;">
<a id="student" href="number?regNo=<c:out value="${studentList.regNo}"/>">
<span class="eachStudent">
<span class="studentName"><c:out value="${studentList.name}"/></span><br/>
<span class="collName"><c:out value="${studentList.collName}"/></span><br/>
<span class="deptName"><c:out value="${studentList.deptName}"/></span><br/>
</span>
</a>
</td>
</tr>
</c:forEach>
The above c:forEach lists
Name CollName DeptName
ABCD coll1 dept1
kfkdb coll1 dept2
jbdd coll2 dept3
Following is the code that lists the collName and deptName respectively.
<div>
Filter students by College (not required):
<select id="byCollege" name="byCollege" >
<c:forEach items="${uniqueCollList}" var="uniqueCollList">
<option value="${uniqueCollList}"/>
${uniqueCollList}</option >
</c:forEach >
</select >
</div>
<div>
Filter students by Department Name (not required):
<select id="byDept" name="byDept" >
<c:forEach items="${uniqueDeptList}" var="uniqueDeptList">
<option value="${uniqueDeptList}"/>
${uniqueDeptList}</option >
</c:forEach >
</select >
</div>
Now when I select a value from first dropdown, I want to filter the results given by foreach using the value selected in dropdown. I would like to do this in front end itself, rather going to the back end. May I know how can I do this?
After filtering the c:foreach result using value of first dropdown, if I select a value in second dropdown, I want the updated result of c:foreach to be filtered using the value selected in second drop down.
How can I do this?
If I want to do this in back end, what should I do?
PS:Following is the controller code that sends the list first time
#RequestMapping(value = "/name", method = RequestMethod.POST, params = { "studentName" })
public String searchStudentByCollOrDept(#RequestParam(value = "studentName", required = true)String studentName, ModelMap model){
List<OneStudentResult> nameList = resultService.getStudentList(studentName);
//TODO, null value check.
if(nameList.size() == 0 || nameList == null){
return "header";
}
if(nameList.size() != 0){
// Iterate the list that we get and add only one time a collName and deptname.So a Treeset.
Set<String> uniqueCollList = new TreeSet<String>();
Iterator<OneStudentResult> itr = nameList.iterator();
while(itr.hasNext()){
String collName = itr.next().getCollName();
if(!uniqueCollList.contains(collName)){
uniqueCollList.add(collName);
}
}
uniqueCollList.add(" Select a College ");
model.addAttribute("uniqueCollList", uniqueCollList);
Set<String> uniqueDeptList = new TreeSet<String>();
Iterator<OneStudentResult> itrDeptList = nameList.iterator();
while(itrDeptList.hasNext()){
String deptName = itrDeptList.next().getDeptName();
if(!uniqueDeptList.contains(deptName)){
uniqueDeptList.add(deptName);
}
}
uniqueDeptList.add(" Select a Department ");
model.addAttribute("uniqueDeptList", uniqueDeptList);
}
model.addAttribute("nameList", nameList);
return "nameResult";
}
I'm afraid there is no simple solution to your problem. You should consider doing this server-side with ajax updates. Client side filtering would either require you to parse the data from the HTML generated by your studentList or it would require you to inject the data as a JSON formatted array. In both cases you would end up with doubled data (server & client). Having the data on the client-side would only allow you to disable some of the option values, not hide them. So if you want real filtering in terms of not-showing some of the options then you should filter your lists on the server. To do so you should post the selected option from your first dropdown "byCollege" to your backend in order to retrieve a filtered "uniqueDeptList" that you use to rebuild the "byDept" checkbox. You might want to use jQuery for both tasks.
Steps:
1. Handle the change-event of the "byCollege" dropdown
2. Post the selected option value to your servlet
3. Filter the data in your servlet and return the filtered data as POST response (omitted in this example)
4. Remove the old select options and recreate them from the filtered data
$("#byCollege").change(function() {
$("select option:selected").first().each(function() {
// Get and convert the data for sending
// Example: This variable contains the selected option-text
var outdata = $(this).text();
// Send the data as an ajax POST request
$.ajax({
url: "yourjsonservlet",
type: 'POST',
dataType: 'json',
data: JSON.stringify(outdata),
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
// Remove old select options from the DOM
$('#byCollege')
.find('option')
.remove()
.end();
// Parse data and append new select options
//(omitted here; e.g. $('#byCollege').append($("<option>").attr(...))
},
error: function(data, status, er) {
alert("error: " + data + " status: " + status + " er:" + er);
}
});
});
});

how to make changes the value of one combobox when another changed in Struts2

Actually i've two comboboxes.First one contains the countries list,and second one contains the states list.. if i click the particular country,the 2nd combobox should only show the states related to selected particular country only.
how to do this in Struts2 jsp form,thanks in advance.....
you can do this of status with javascript :
if( document.getElementById("combo..1").value =="1thvalue" ) {
document.getElementById("combo..2").value =="2thvalue"
}
Assuming you have jQuery, try this:
<select id="country">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<select id="state"></select>
var data = ["state1", "state2", "state3"];
$("#country").change(function(){
// get data with $.ajax ..
var option;
$.each(data, function(index, value){
option += "<option>" + value + "</option>";
});
$("#state").empty().append(option);
});
You can try it out here: http://jsfiddle.net/jaiwo99/fgt5R/
html code
<select id="country">
<option>India</option>
<option>Pak</option>
<option>UK</option>
</select>
<select id="state"></select>
Jquery
var data = [
{"India":"tamilnadu"}
,{"Pak": "lokur"},{"UK" :"london"}
]; // Json data
$("#country").change(function(){
var option;
$.each(data, function(index, value){
$.each(value,function(countr,stat){
var x=$("#country").val();
if(x==countr){
$("#state").empty();
$("#state").append("<option>"+stat+"</option>");
}
});
});
});

Passing a Java string to Javascript

I am trying to load a table with data by initializing a Javascript variable with a string in JSON format. If I declare:
<script type="text/javascript">
var data = new String("{totalCount: '1', identifier: 'EntityID', items: [{'EntityID':'1','Country':'United States','Region':'','State':'California','County':'Santa Clara','City':'San Jose','ZipCode':'95134'}]}");
var d3 = eval('(' + data + ')');
<span dojoType="dojo.data.ItemFileWriteStore" jsId="dataStore" data=d3></span>
</script>
then my table will correctly load the row.
I have tried initializing a Java string before my script and then passing that object into a Javascript variable like so:
<%
String d = "{totalCount: '1', identifier: 'EntityID', items: [{'EntityID':'1','Country':'United States','Region':'','State':'California','County':'Santa Clara','City':'San Jose','ZipCode':'95134'}]}";
%>
<script type="text/javascript">
var data = new String(<%=d%>);
// var data = new String(d) // tried this as well
var d3 = eval('(' + data + ')');
<span dojoType="dojo.data.ItemFileWriteStore" jsId="dataStore" data=d3></span>
</script>
My table does not recognize this and is unable to load the row when I attempt to pass it this way. How can I properly pass a Java string to Javascript so that my table will be able to load the data?
Try with quotes around.
var data = new String("<%= d %>");

Categories

Resources