Using jQuery + JSON + Struts to populate select options based on input textfield - java

I am trying to implement an ajax call to populate the options of a select drop down based on the input textfield. Any help would be appreciated on this.
This is my method which allows us to get the template for a number .
System.out.println("Getting template for " + no_nego);
//Do the database code or business logic here.
try {
Connection con;
con = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:8081/RSI_MANAGEMENT", "root", "user");
Statement stmt = null;
stmt = con.createStatement();
String tableName = "rsi_demande";
String sql;
sql = "select filename from " + tableName +
" Where (filename IS NOT NULL and no_negociateur=" + getNo_nego() + " ) ";
ResultSet res = null;
res = stmt.executeQuery(sql);
while (res.next()) {
listeTemplateDownload.add(res.getString(1));
}
//setListeTemplateDownload(listeTemplateDownload);
stmt.close();
} catch (Exception ex1) {
ex1.printStackTrace();
}
for (int i = 0; i < 2; i++)
System.out.println(listeTemplateDownload.get(i));
JSONArray json = new JSONArray();
json.addAll(getListeTemplateDownload());
json.toString();
System.out.printf("JSON: %s", json.toString());
return Action.SUCCESS;
}
And here is my jsp page :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<script src="js/jquery-1.11.1.min.js"></script>
</head>
<body>
<script>
$(function() {
$("#no_nego").change(
function() {
var state = {
"no_nego": $("#no_nego").val()
};
$.ajax({
url: "readDistricts",
data: JSON.stringify(state),
dataType: 'JSON',
contentType: 'application/json',
type: 'POST',
async: true,
success: function() {
var $select = $('#listeTemplateDownload');
$select.html('');
console.log(listeTemplateDownload.size());
for (var i = 0; i < getListeTemplateDownload().size(); i++) {
$select.append(
'<option value= ' + listeTemplateDownload.get(i) + '</option>');
}
}
});
});
});
</script>
<h3>Struts 2 Dynamic Drop down List</h3>
State :
<input type="text" id="no_nego"></select> District :
<select id="listeTemplateDownload"></select>
</body>
</html>
I want that when a user finished set number, the list will be generated dynamically ...
But how can i populate select form with these data?

Solved .
The problem was the append method :
jsp :
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<script src="js/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function () {
$('#listeTemplateDownload').html('');
$("#no_nego").change(
function() {
var no_nego = {
"no_nego" : $("#no_nego").val()
};
$.ajax({
url : "readDistricts.action",
data : JSON.stringify(no_nego),
dataType : 'json',
contentType : 'application/json',
type : 'post',
async : true,
success : function(res) {
console.log(res.listeTemplateDownload.length);
for ( var i = 0; i < res.listeTemplateDownload.length; i++) {
$('#listeTemplateDownload').append( '<option value=' + res.listeTemplateDownload[i] + '>' + res.listeTemplateDownload[i] + '</option>');
}
}
});
});
});
</script>
</head>
<body>
<h3>Struts 2 Dynamic Drop down List</h3>
Negociateur n°:
<input type="text" id="no_nego" > Template :
<select id="listeTemplateDownload"></select>
</body>
</html>

Related

Parse HTML(web-page) JavaSE

I need to create web scraper utility which get web resources by URL. Then count number of provided word(s) occurrence on webpage and number of characters.
URL url = new URL(urlStr);
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
With that I can get all text on page(and html tags) so what I do next?
Can someone help me with that? Some doc or sthg to read. I need use only JavaSE. Can't use 3d party library.
For example, you have page.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Page</title>
</head>
<body>
<div id="login" class="simple" >
<form action="login.do">
Username : <input id="username" type="text" />
Password : <input id="password" type="password" />
<input id="submit" type="submit" />
<input id="reset" type="reset" />
</form>
</div>
</body>
</html>
To parse it you can with:
import java.io.File;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
/**
* Java Program to parse/read HTML documents from File using Jsoup library.
*/
public class HTMLParser{
public static void main(String args[]) {
// Parse HTML String using JSoup library
String HTMLSTring = "<!DOCTYPE html>"
+ "<html>"
+ "<head>"
+ "<title>JSoup Example</title>"
+ "</head>"
+ "<body>"
+ "<table><tr><td><h1>HelloWorld</h1></tr>"
+ "</table>"
+ "</body>"
+ "</html>";
Document html = Jsoup.parse(HTMLSTring);
String title = html.title();
String h1 = html.body().getElementsByTag("h1").text();
System.out.println("Input HTML String to JSoup :" + HTMLSTring);
System.out.println("After parsing, Title : " + title);
System.out.println("Afte parsing, Heading : " + h1);
// JSoup Example 2 - Reading HTML page from URL
Document doc;
try {
doc = Jsoup.connect("http://google.com/").get();
title = doc.title();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Jsoup Can read HTML page from URL, title : " + title);
// JSoup Example 3 - Parsing an HTML file in Java
//Document htmlFile = Jsoup.parse("login.html", "ISO-8859-1"); // wrong
Document htmlFile = null;
try {
htmlFile = Jsoup.parse(new File("login.html"), "ISO-8859-1");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // right
title = htmlFile.title();
Element div = htmlFile.getElementById("login");
String cssClass = div.className(); // getting class form HTML element
System.out.println("Jsoup can also parse HTML file directly");
System.out.println("title : " + title);
System.out.println("class of div tag : " + cssClass);
}
}
Output:
Input HTML String to JSoup :<!DOCTYPE html><html><head><title>JSoup Example</title></head><body><table><tr><td><h1>HelloWorld</h1></tr></table></body></html>
After parsing, Title : JSoup Example
Afte parsing, Heading : HelloWorld
Jsoup Can read HTML page from URL, title : Google
Jsoup can also parse HTML file directly
title : Login Page
class of div tag : simple

Pagination: how to load first page with AJAX

I'm writing online shopping application using Struts 2.
In front-end I'm using jsp, twitter bootstrap, jquery, moustache.js template, twbs pagination plugin and some javascript.
I have Product entity and I want to display the list of products to the user in jsp page.
The way I'm doing it is async loading page with fix number(20) of products in json format and then obtaining them using mustache template.
All my code works except the time when user the first time sees this jsp page - first 20 products are not displaying. So when I'm moving from page to page it loads info, but as twbs plugin works through firing events it means that event is not triggered after jsp page loaded the first time.
So my question is whats the truly good way to fix this ?
Should I fire an event once or use $(document).ready() or $(document).onload() ?
I'm not an expert in javascript, so please be patient
<html>
<%# include file="/WEB-INF/jspf/head.jspf"%>
<body>
<%# include file="/WEB-INF/jspf/menu.jspf"%>
<div class="container">
<ul class="sync-pagination pagination"></ul>
<div id="products" style="width: 50%"></div>
<ul class="sync-pagination pagination"></ul>
</div>
<script type="text/javascript"
src="webjars/mustachejs/0.8.2/mustache.js"></script>
<script id="products-template" type="text/mustache-template">
<ul class="list-group">
{{#.}}
<li class="list-group-item">
<label for="{{name}}">Name: /label> {{name}}
</br>
<label for="{{price}}">Price: </label> {{price}}
</br>
Full description...
</li>
{{/.}}
</ul>
</script>
<script type="text/javascript"
src="script/jquery.twbsPagination.min.js"></script>
<script type="text/javascript">
var records = "${requestScope.records}";
var recordsPerPage = 20;
var pages = Math.ceil(records / recordsPerPage);
$('.sync-pagination').twbsPagination({
totalPages : pages,
visiblePages : 7,
onPageClick : function(event, page) {
$('#products').html(changePage(page));
}
});
function changePage(page) {
pnumber = page || 1;
$.ajax({
type : 'GET',
dataType : 'json',
url : 'product/upload_products?page=' + pnumber,
success : function(products) {
var template = $('#products-template').html();
var info = Mustache.render(template, products);
$('#products').html(info);
}
})
}
</script>
</body>
</html>
You need to call changePage(); on the initial load. You might also want to call this when the page finishes loading everything by using $(document).ready();
<script type="text/javascript">
var records = "${requestScope.records}";
var recordsPerPage = 20;
var pages = Math.ceil(records / recordsPerPage);
$('.sync-pagination').twbsPagination({
totalPages : pages,
visiblePages : 7,
onPageClick : function(event, page) {
$('#products').html(changePage(page));
}
});
function changePage(page) {
pnumber = page || 1;
$.ajax({
type : 'GET',
dataType : 'json',
url : 'product/upload_products?page=' + pnumber,
success : function(products) {
var template = $('#products-template').html();
var info = Mustache.render(template, products);
$('#products').html(info);
}
})
}
//Add this in here
changePage();
</script>

How to fetch value of dynamically created textbox in jsp

I am creating a social networking site and I am facing one problem.
I am fetching records from database and with each record I want to add one button so that I can change that record using that text box.
But when I am updating record using that text box, it is getting value of the first text box only. If I am updating 2, 3, 4, 5 etc record then it is getting value of first text box.
So please help me how can I get value of each and every text box - not just from the first one.
Thanks in advance.
Below is my code:
<%
Statement st1;
ResultSet rs1;
Connection con;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dfmc","root","93Pb3gaNv0");
String sql1="select * from user_table LIMIT 5";
st1 = con.createStatement();
rs1=st1.executeQuery(sql1);
String id=null,name=null;
while(rs1.next()){
id=rs1.getString("id");
name=rs1.getString("first_name");
%>
<div><input type="text" name="txt" id="name" />
<input type="button" name="btn" value="Rating" onclick="loadXMLDoc(<%=id%>)">
<p id="showname"><%=name%></p>
</div>
<script type="text/javascript">
function loadXMLDoc(iid){
var idd=iid;
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("showname").innerHTML=xmlhttp.responseText;
}
}
var name;
name = document.getElementById("name").value;
xmlhttp.open("GET", 'insert_rating?name='+name+'&id='+idd+'', true);
xmlhttp.send();
}
</script>
I was also facing the same problem, but I could easily get javascript dynamic text box value on servlet, by using request.getParameterValues("DynamicTextBox");
client side code:
$("#btnGet").bind("click", function () {
var values = "";
$("input[name=DynamicTextBox]").each(function () {
values += $(this).val() + "\n";
});
alert(values);
});
});
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" type="text" value = "' + value + '" /> ' +
'<input type="button" value="Remove" class="remove" />'
}
server side code (servlet):
String[] duration= request.getParameterValues("DynamicTextBox");
for (String string : duration) {
System.out.println("Duration1=="+string);
}

Display select List through iteration

<%# page import="java.sql.*" %>
<%# page import="javax.sql.*" %>
<%# page import="java.util.*" %>
<%
Connection con =null;
PreparedStatement pstmt=null;
List<String> list=null;
ResultSet rs=null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "xyz", "abc");
String strQuery = "SELECT batch_id,course_name FROM t_students_batch";
pstmt = con.prepareStatement(strQuery);
rs = pstmt.executeQuery();
list = new ArrayList<String>();
while(rs.next()) {
list.add(rs.getString("batch_id"));
list.add(rs.getString("course_name"));
}
}catch(Exception e) {
System.out.println("Error:: "+e.getMessage());
}
%>
<html>
<head>
<title>pay</title>
</head>
<body>
<form action="payment.jsp" method="get">
BatchId ::<select name="batchid">
<%
for (String temp : list) {
// how to i get this..
out.println("<option>"+ temp +"</option>");
}
%>
<input type="submit" value="continue" action="payment.jsp" />
</select>
</form>
</body>
</html>
output :::
1 java
2 jsp
Total column values are displaying like this
When I click the "1" it's working...
When I click the java or jsp, it will show me a null pointer exception..
I want to take the java value 1 display as it is the logic..
Try this one.
<%
for (int i = 0; i < list.size(); i = i+2) {
out.println("<option value='"+list.get(i) +"'>"+ list.get(i+1) +"</option>");
}
%>
missing value attr , now it should submit value.
<%
for (String temp : list) {
// how to i get this..
out.println("<option value='"+temp +"'>"+ temp +"</option>");
}
%>

Jquery Autocomplete not passing values to java

I've created autocomplete with Jquery UI library and try to get the text box value in java, but not getting the value instead of getting null value. Please help to get value from text box. This is the line String query = (String)request.getParameter("country"); not getting values ?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<style>
input {
font-size: 120%; }
</style>
</head>
<body>
<h3>Feature</h3>
<input type="text" id="country" name="country"/>
<script>
//$("#country").autocomplete("getdata.jsp");
$("#country").autocomplete({
source: "getdata.jsp",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
</script>
</body>
</html>
getdata.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*"%>
<%#page import="java.util.*"%>
<%
String query = (String)request.getParameter("country");
System.out.println("query"+query);
try{
String s[]=null;
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =DriverManager.getConnection("XXXXX");
Statement st=con.createStatement();
ResultSet rs = st.executeQuery("select name from table1 where name like '"+query+"%'");
List li = new ArrayList();
while(rs.next())
{
li.add(rs.getString(1));
}
String[] str = new String[li.size()];
Iterator it = li.iterator();
int i = 0;
while(it.hasNext())
{
String p = (String)it.next();
str[i] = p;
i++;
}
//jQuery related start
int cnt=1;
for(int j=0;j<str.length;j++)
{
if(str[j].toUpperCase().startsWith(query.toUpperCase()))
{
out.print(str[j]+"\n");
if(cnt>=5)// 5=How many results have to show while we are typing(auto suggestions)
break;
cnt++;
}
}
//jQuery related end
rs.close();
st.close();
con.close();
}
catch(Exception e){
e.printStackTrace();
}
%>
it's not a form,so don't get the value use getParameter().
source: "getdata.jsp?country="+$("#country").val(),

Categories