I am new to java and want to create an editable combobox in which when user types in it the results come from database.
Like if I type "e" in combobox then all the name starting with "e" should come from database.
Please give a simple example.
You can use jQuery plugins, following example is for php just replace the php parts with java code, or have a look at this.
With JSON
$(document).ready(function() {
$(function() {
$("#search").autocomplete({
source : function(request, response) {
$.ajax({
url : "SearchController",
type : "GET",
data : {
term : request.term
},
dataType : "json",
success : function(data) {
response(data);
}
});
}
});
});
});
With DB
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Remote datasource</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
.ui-autocomplete-loading {
background: white url("images/ui-anim_basic_16x16.gif") right center no-repeat;
}
</style>
<script>
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#birds" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds">
</div>
<div class="ui-widget" style="margin-top:2em; font-family:Arial">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
</body>
</html>
Related
I tried to fetch data from mysql, h2, derby databases but nothing worked. I tried exactly as it was given on w2schools website. But later I thought I would try with Array Function and check with Java JSP page in my AngularJS page calling it.
Below is the index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
<script src="angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<table>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
</tr>
</table>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://localhost:8080/pavanjsp/jsondata.jsp")
.then(function (response) {$scope.names = response.data.records;});
});
</script>
</body>
</html>
Here is my jsondata.jsp below:
<%# page contentType="text/html; charset=iso-8859-1" language="java" %>
<html>
<head>
<title>JSON Data</title>
<link rel="stylesheet" href="dist/css/bootstrap.css" />
</head>
<body>
<div class="container-fluid">
<%
String[] names = { "Alfreds Futterkiste", "B's Beverages", "Berglunds snabbköp", "Blondel père et fils", "Bólido Comidas preparadas", "Bon app'", "Comércio Mineiro" };
response.addHeader("Access-Control-Allow-Origin", "*");
%>
<%
out.print("{ \"records\":[ ");
for(int i = 0; i < names.length; i++)
{
if(i == (names.length - 1))
out.print("{\"Name\":\"" + names[i] + "\"}");
else
out.print("{\"Name\":\"" + names[i] + "\"}, ");
}
out.print(" ] }");
%>
</div>
</body>
</html>
I even tried putting the index.html as index.jsp and deploying in tomcat. But doesn't works. Even Php code I have tried but not working.
Please help me out.
Ok I got my own answer, and thanks cyan for the help. The issue was with the response, the updated code is as below:
jsaondata.jsp(hosted on tomcat)
<%# page contentType="application/json; charset=iso-8859-1" language="java" %>
<%
String[] names = { "Alfreds Futterkiste", "B's Beverages", "Berglunds snabbköp", "Blondel père et fils", "Bólido Comidas preparadas", "Bon app'", "Comércio Mineiro" };
response.addHeader("Access-Control-Allow-Origin", "*");
%>
<%
out.write("{ \"records\":[ ");
for(int i = 0; i < names.length; i++)
{
if(i == (names.length - 1))
out.write("{\"Name\":\"" + names[i] + "\"}");
else
out.write("{\"Name\":\"" + names[i] + "\"}, ");
}
out.write(" ] }");
%>
angulardata.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
<script src="angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<table>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
</tr>
</table>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://localhost:8080/pavanjsp/jsondata.jsp")
.then(function (response) {$scope.names = response.data.records;});
});
</script>
</body>
</html>
Try changing code to:
$scope.names = JSON.parse(response.data).records;
If this doesn't work, debug if you receive proper json from server.
Open some firebug/developer tools ( usually f12) and see network.
Open page and see response. Copy it and paste to some json validation tool.
If JSON is proper, then something is wrong in angular app, but i see that everything is fine.
Also check in firebug this call, if there is properly CORS configured.
If you receive result 200 ok, then it's fine.
Also you can use $log service to debug your result:
app.controller('customersCtrl', function($scope, $http,$log)
.then(function (response) {$log.debug('response',response);
I hope it helps.
here the fields are hard coded but i want to get the fields dynamically for my task,like i will have a list in this jsp which contains field names eg: list=[id,name,salary,doj] this list may change for new requests. Can i have some ideas to do this
fields: {
PersonId: {
key: true,
create: false,
edit: false,
list: false
},
Name: {
title: 'Author Name',
width: '40%'
},
Age: {
title: 'Age',
width: '20%'
},
Watch: {
title: 'Watch',
width: '20%',
display: function (data) {
return '';
},
RecordDate: {
title: 'Record date',
width: '30%',
type: 'date',
create: false,
edit: false
}
}
});
You can build Javascript code dynamically on server side.
For client side, you can also create fields dynamically.
var fields = {
PersonId: { //I assume that this field is standard
key: true,
list: false
}
};
if(someCondition) {
fields['Name'] = {
title: 'Author Name',
width: '40%'
};
}
//Add other dynamic fields
$('#PersonTableContainer').jtable({
title: 'Table of people',
actions: {
listAction: '/GettingStarted/PersonList',
createAction: '/GettingStarted/CreatePerson',
updateAction: '/GettingStarted/UpdatePerson',
deleteAction: '/GettingStarted/DeletePerson'
},
fields: fields
});
In your condition, you can add fields from a list surely.
I was posting whole code by taking reference of above answer
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.List"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Setup and Load Data to jTable using Servlets and JSP</title>
<!-- Include one of jTable styles. -->
<link href="css/metro/crimson/jtable.css" rel="stylesheet" type="text/css" />
<link href="css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" />
<!-- Include jTable script file. -->
<script src="js/jquery-1.8.2.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
<script src="js/jquery.jtable.js" type="text/javascript"></script>
<script type="text/javascript">
<% List<String> strList = new ArrayList<String>();
strList.add("one");
strList.add("two");
strList.add("three"); %>
var jsArray = [<% for (int i = 0; i < strList.size(); i++) { %>"<%= strList.get(i) %>"<%= i + 1 < strList.size() ? ",":"" %><% } %>];
var fields = {
};
var arrayLength = jsArray.length;
for(var i=0;i<arrayLength;i++)
{
fields[jsArray[i]] = {
title: jsArray[i],
width: '40%'
};
}
$(document).ready(function () {
$('#PersonTableContainer').jtable({
title: 'Table of people',
actions: {
listAction: 'CRUDController?action=list',
createAction:'CRUDController?action=create',
updateAction: 'CRUDController?action=update',
deleteAction: 'CRUDController?action=delete'
},
fields:fields
});
$('#PersonTableContainer').jtable('load');
});
</script>
</head>
<body>
<div style="width:60%;margin-right:20%;margin-left:20%;text-align:center;">
<div id="PersonTableContainer"></div>
</div>
</body>
</html>
i have written a small code which inclued 2 jsp pages and
1) test2.jsp --> i have made a dropdown in this page
2) test3.jsp --> displays a welcome message when the person selects an option from the dropdown ,
he will migrate to this page without refreshing test2.jsp
for this i have used ajax jquery
when i click on the submit button nothing happens , please help me with this
i have also put the org.json.jar file in the libraries
test2.jsp code
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//malsup.github.com/jquery.form.js"></script>
<script>
function check()
{
$.ajax({
url: "test3.jsp",
type: "GET",
success: function() {
alert("succes");
},
error: function() {
alert( "Sorry, there was a problem!" );
}
});
}
</script>
</head>
<body>
<h1>Hello World!</h1>
<br>
<form method="post" action="test2.jsp">
<select name="city">
<option value="dropdown">select city</option>
<option value="jal">Jalandhar</option>
<option value="ggn">Gurgaon</option>
<option value="noida">Noida</option>
<option value="amrtsr">Amritsar</option>
<option value="bombay">Bombay</option>
</select>
<input type="submit" value="Submit" onclick="check()">
</form>
test3.jsp code
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>welcome</h1>
</body>
</html>
The function should return false to prevent form submittion
<script>
function check() {
$.ajax({
url: "test3.jsp",
type: "GET",
success: function() {
alert("succes");
},
error: function() {
alert( "Sorry, there was a problem!" );
}
});
return false;
}
</script>
It should be
<input type="button" value="Submit" onclick="check()">
instead of
<input type="submit" value="Submit" onclick="check()">
because submit input type call form's action that is test2.jsp.
call your javascript function on change event of drop down
onchange="check()"
and navigate through firebug and check your consol it will show you your whole ajax request
How to print Google annotated chart by clicking on print button in a web page?
In my code, I used window.print() method, but when I print the page, chart disappears from the webpage and rest of the content is printing.
Please help me.
<!DOCTYPE html> <html> <head>
<title>Google Chart with jsp Mysql Json</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"><!--
css for datepicker -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script><!--
Javascript for datepicker -->
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]}); $(document).ready(function(){
showGoogleChart('2013-12-01','2013-12-31');
//============================= Onpage load calling chart function
$( "#from" ).datepicker({ changeMonth: true,
dateFormat:'yy-mm-dd', numberOfMonths: 3, onClose: function(
selectedDate ) { $( "#to" ).datepicker( "option", "minDate",
selectedDate ); } }); $( "#to" ).datepicker({
dateFormat:'yy-mm-dd', changeMonth: true, numberOfMonths: 3,
onClose: function( selectedDate ) { $( "#from" ).datepicker(
"option", "maxDate", selectedDate ); } }); });
//==================== OnChange date call google chart
================== function getChartdate(){ alert("hi"); var startdate = $('#from').val(); var enddate = $('#to').val();
showGoogleChart(startdate,enddate); //===========On button click
calling chart function========= }
function showGoogleChart(startdate,enddate){
var queryObject="";
var queryObjectLen="";
var postdata = {"startDate":startdate,"endDate":enddate};
$.ajax({
type : 'POST',
url : 'testPages.jsp',
data:postdata,
dataType:'json',
success : function(data) {
queryObject = eval('(' + JSON.stringify(data) + ')');
queryObjectLen = queryObject.empdetails.length;
google.setOnLoadCallback(drawChart(queryObject,queryObjectLen));
},
error : function(xhr, type) {
alert('server error occoured')
}
});
}
function drawChart(queryObject,queryObjectLen) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'date');
data.addColumn('number', 'temp');
for(var i=0;i<queryObjectLen;i++)
{
var name = queryObject.empdetails[i].date;
var empid = queryObject.empdetails[i].temp;
data.addRows([
[name,parseInt(empid)]
]);
}
var options = {
title: 'Employee Information',
}; var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data,options); }
</script>
</head>
<body>
<div style="margin: 50px;">
<label for="from">From</label> <input type="text" id="from" name="from"> <label for="to">to</label> <input type="text"
id="to" name="to"> <input type="button" id="changeChart"
onclick="getChartdate();" value="Change Chart"/>
</div>
<div id="chart_div"></div>
</body>
</html>
The method window print() will simply open the print dialog. How the page is formatted for print depends on how the browser formats webpages and the print stylesheet if present.
Assuming the chart is some kind of image (or canvas), it might be that the browser choses to strip images when printing. Especially if the image is added using css background-image: url(...) because it assumes a background image (like background-color) is just for decoration and would waste ink if printed.
A plain img tag should print though in most cases unless some css is removing it for print...
I am new to ajax and jquery and trying to place an ajax call in my code. But below are the error messages I get when placing alerts:
jqxhr.status = 404
thrown error = Not Found
jqxhr.statusText = Not Found
request = undefined
error = undefined
What I want to do:
Open a modal dialog with just a Fancy text box (Tinymce) on click of an "Edit gif". After the contents are edited in the textbox, and the "Save" button in the modal dialog is clicked, initiate an ajax call to save the contents in the Database.
What is happening:
The modal dialog opens correctly, I am able to see that the "data" part for the ajax call is populated correctly (placed alerts to confirm). I believe the url is also correct. If I type the url in a browser, the control does go to my servlet as per web.xml (Sysout in Servlet gets printed). But somehow, the ajax call never goes through to the server after click of "Save" button. Will be really great if one of you can help me out here, will greatly appreciate it. My JSP (copied what I feel is relevant alone):
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<link rel="stylesheet" type="text/css" href="css/sis.css" media="screen" />
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/css/jquery-ui-1.10.3.custom">
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-ui.min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/tinymce/tinymce.min.js"></script>
<script>
$(function() {
$("#dialog-form2").dialog({
autoOpen: false, width: 500, modal: true,
buttons: {
"Save": function() {
tinymce.get("stChallenge").setContent(tinyMCE.get("edChallenge").getContent());
alert($("#ChalId").val());
alert(tinyMCE.get("edChallenge").getContent());
var xhr =
$.ajax({
url: "/AjaxServlet?method=updateChal&keyword=dummy",
type: "GET",
data: {
CommentId: $("#ChalId").val(),
challenge: tinyMCE.get("edChallenge").getContent()
},
success: function (result) {
alert("Success :" + result);
$(this).dialog("close");
},
error:function (jqxhr, ajaxOptions, thrownError, request, error) {
alert('jqxhr.status = ' + jqxhr.status + '\n' + 'thrown error = ' + thrownError + '\n' + 'jqxhr.statusText = ' + jqxhr.statusText + '\n' +
'request = ' + request + '\n' + 'error = ' + error);
$(this).dialog("close");
}
});
},
Cancel: function() {
$(this).dialog("close");
}
},
close: function() {
}
});
$("#Edit2")
.click(function() {
$("#dialog-form2").dialog("open");
});
});
</script>
<script type="text/javascript">
tinymce.init({
selector: "#edChallenge", theme: "modern",
plugins: [
],
image_advtab: false
});
</script>
<script type="text/javascript">
tinymce.init({
selector: "#stChallenge", theme: "modern", readonly: true, toolbar: "false", menubar: "false",
plugins: [
],
image_advtab: false
});
</script>
</head>
<body>
<c:set var="model" value="${sessionScope.model}" />
<html:form action="managePerf.do?method=showPerf" method="post" styleId="ManagePerfForm">
<html:errors/>
Date: <html:text property="rankDate" styleId="datepicker" name="ManagePerfForm" />
<html:submit value="Go" styleClass="input button"/>
<fieldset>
<table border="0">
<tr>
<td>
<div id="dialog-form2" title="Edit Challenges">
<form>
<textarea cols="75" rows="50" id="edChallenge">${comments}</textarea>
</form>
</div>
<label>Challenges</label>
<a href="javascript:void(0);" id="Edit2">
<img src='${pageContext.request.contextPath}/img/Edit.gif' height="32" width="32"/>
</a>
<div id="dTextBox" class="ui-widget">
<textarea cols="75" rows="15" id="stChallenge" readonly="true">${comments}</textarea>
</div>
<input type="hidden" id="ChalId" value=${CommentId} />
</td>
</tr>
</table>
</fieldset>
</html:form>
</body>