I have a Thymeleaf form.
One of the input fields is like this:
<input type ="text" id="customer" class="floatLabel" name="customer" th:field = "*{customer.idCustomer}">
<label for="customer">Customer</label>
I want to use jQuery UI. In my Java app, it works and the app sends JSON with correct values. But my auto suggestion list is empty.
I included one css library in my html head section and few script libraries at the bottom of body part.
Libraries are:
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
jQuery code:
<script>
$("#customer").autocomplete({
source: function( request, response ) {
$.ajax({
url: "/search_customer",
type: 'post',
dataType: "json",
data: {
search: request.term
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
// Set selection
$('#customer').val(ui.item.value); // save selected id to input
$('#customer').val(ui.item.label); // display the selected text
return false;
}
});
Java controller:
#PostMapping("/search_customer")
#ResponseBody
public List<Object[]> searchTerm(#RequestParam(name = "search", required = false) String searchTerm)
{
List<Object[]> customers = customerDAO.getCustomers(searchTerm);
return customers;
}
JpaRepository:
#Repository
public interface ICustomerRepository extends JpaRepository<CustomerDTO, Integer>
{
#Query(value = "SELECT c.idCustomer, c.ingameName FROM CustomerDTO c WHERE c.ingameName LIKE :term%")
public List<Object[]> findCustomersAutocomplete(String term);
}
So, everything works fine, I get JSON array and each element has one integer and one string. In that thymeleaf input field I want labels to be string "ingameName" and value (user shouldn't see that) is idCustomer.
JSON that I received looks like this:
[[1, "customer1"], [3, "Customer2"]]
0: [1, "customer1"]
0: 1
1: "customer1"
1: [3, "Customer2"]
0: 3
1: "Customer2"
So I want labels to be customer1 and Customer2 and values that should be saved are 1 or 3.
But I don't know how to tell jQuery UI what is label and what is id?
I followed this tutorial:
https://makitweb.com/jquery-ui-autocomplete-with-php-and-ajax/
As your data recieve from backend(controller) is not in format which autocomplete plugin accept so you can create that format inside success function of ajax . You just need to loop through your data using each loop and then push array value in key-value pair in JSON Array and then pass same to your plugin.
Demo Code :
var data = [
[1, "Customer1"],
[3, "Customer2"]
];
$("#customer").autocomplete({
source: function(request, response) {
/*$.ajax({
//some codes
success: function( data ) {*/
var json_array = [];
//create format like autocompltee
$(data).each(function(i, val) {
//create obj and push value in main_array
json_array.push({
"label": val[1],
"value": val[0]
})
})
console.log(json_array)
response(json_array);
/* }
});*/
},
select: function(event, ui) {
$('#customer').val(ui.item.label);
$('#ids').val(ui.item.value);
return false;
}
});
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<input type="text" id="customer" class="floatLabel" name="customer">
<input type="text" id="ids">
<label for="customer">Customer</label>
I am going to implement a search form as in here. As you can see the first dropdown box is used to select a country. Once a country is selected the list of its cities will be populated into second dropdown list. Please note the second dropdown list is disabled first and will be enabled when it is populated by data.
To implement this, onChange function is used to send the selected value of the first dropdown list to the server and retrieve the results but I do not know how to populate the second dropdown list.
<s:form action="/Cars/find" method="GET">
<s:select id="country"
name="country"
list="#com.example.listOfCountries"
onChange="getCities(this.value)"
/>
<s:select id="city"
name="city"
headerKey="-1" headerValue="Select City"
disabled = "true"
list="{'empty'}";
/>
<s:submit value="Search"></s:submit>
</s:form>
JavaScript function
function getCities(val) {
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("carCity").disabled = "false";
document.getElementById("carCity").list = xmlhttp.responseText;
}
}
xmlhttp.open("get", "../Search/findCities?country=" + val, false);
xmlhttp.send();
}
Java
my Java function add the list of cities to the following field
private List<String> cities = new ArrayList();
And show them into result page using
${cities}
Output of the xmlhttp.responseText
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
[{, 'Aberdeen', 'Aberystwyth', 'Aldershot', 'Amesbury', 'Anglesey', 'Ashford', 'Aylesbury', 'Ayr', 'Banbury', 'Barnstaple', 'Barrow In Furness', 'Basildon', 'Basingstoke', 'Bath', 'Bedford', 'Belfast', 'Birkenhead', 'Birmingham', 'Blackpool', 'Bolton', 'Bournemouth', 'Bracknell', 'Bradford', 'Brighton', 'Bristol', 'Bromley', 'Burnley', 'Burton Upon Trent', 'Bury St. Edmunds', 'Caernarfon', 'Cambridge', 'Cardiff', 'Carlisle', 'Carmarthen', 'Chatham', 'Chelmsford', 'Cheltenham', 'Chester', 'Colchester', 'Colwyn Bay', 'Coventry', 'Crawley', 'Croydon', 'Darlington', 'Dartford', 'Derby', 'Derry', 'Doncaster', 'Dover', 'Dudley', 'Dumbarton', 'Dumfries', 'Dundee', 'Durham Tees Valley', 'Eastbourne', 'East Kilbride', 'East Midlands', 'Edinburgh', 'Elgin', 'Epsom', 'Exeter', 'Falkirk', 'Falmouth', 'Fareham', 'Farnborough', 'Feltham', 'Fishguard', 'Fraserburgh', 'Glasgow', 'Glasgow Prestwick', 'Gloucester', 'Godalming', 'Great Yarmouth', 'Grimsby', 'Guernsey', 'Guildford', 'Gwynedd', 'Hamilton', 'Hampton', 'Harlington / Hayes', 'Harlow', 'Harrogate', 'Harrow', 'Hastings', 'Helston', 'Hemel Hempstead', 'Hereford', 'High Wycombe', 'Hoddesdon', 'Holyhead', 'Huddersfield', 'Hull', 'Humberside', 'Ilchester', 'Inverness', 'Ipswich', 'Isle of Man', 'Jersey', 'Kent', 'Kilmarnock', 'Kings Lynn', 'Kirkcaldy', 'Lancaster', 'Lancing', 'Leeds', 'Leicester', 'Lincoln', 'Liverpool', 'Livingston', 'Llandudno', 'London', 'London City Airport', 'London Gatwick Airport', 'London Heathrow Airport', 'London Luton Airport', 'London Stansted Airport', 'Lowestoft', 'Luton', 'Macclesfield', 'Maidstone', 'Manchester', 'Mansfield', 'Middlesbrough', 'Milton Keynes', 'Motherwell', 'Newbury', 'Newcastle Upon Tyne', 'Newport', 'Newquay', 'Northampton', 'Northwich', 'Norwich', 'Nottingham', 'Oldbury', 'Oldham', 'Oxford', 'Paisley', 'Pembroke', 'Penrith', 'Penzance', 'Perth', 'Peterborough', 'Peterhead', 'Plymouth', 'Poole', 'Portsmouth', 'Preston', 'Reading', 'Redditch', 'Reigate', 'Rochdale', 'Rochester', 'Romford', 'Rutland', 'Salisbury', 'Sheffield', 'Shetland Islands', 'Shrewsbury', 'Slough', 'Southampton', 'Southend', 'Southend-on-Sea', 'Stafford', 'Staines', 'St. Albans', 'Stansted', 'Stevenage', 'Stirling', 'Stockport', 'Stockton On Tees', 'Stoke-On-Trent', 'Stranraer', 'Stratford Upon Avon', 'Sunbury', 'Sunderland', 'Sutton', 'Swansea', 'Swindon', 'Tamworth', 'Taunton', 'Teesside', 'Telford', 'Thetford', 'Tonbridge', 'Torquay', 'Truro', 'Uxbridge', 'Wakefield', 'Walsall', 'Warrington', 'Warwick', 'Watford', 'Wellingborough', 'Welshpool', 'Welwyn Garden City', 'West Bromwich', 'Weston-Super-Mare', 'Wetherby', 'Weymouth', 'Wigan', 'Woking', 'Wolverhampton', 'Worcester', 'Workington', 'Worthing', 'Worthing Lancing', 'Yeovil', 'York', }]
</body>
</html>
It appears that you are on the right track, however, I would suggest that you take a look at using a framework like jQuery because this task would be much simpler.
First off, looking at the xmlhttp.responseText, it appears that you need to change your struts configuration so that the output is not a full HTML document. The way the server is returning this response is going to make it very difficult for you to process. A quick way to make this work the way you want is to have the server generate a populated select tag. When your source page renders, place a disabled select tag inside of a div element that you can reference by an ID like so -
<div id="dynamicSelectTagHolder">
<select name="foo" disabled="true" />
</div>
Once the server has generated a result, you can assign the contents of the div#dynamicSelectTagHolder to the text returned by the server using innerHTML like so -
document.getElementById("dynamicSelectTagHolder").innerHTML = xmlhttp.responseText;
Be forewarned you may run into many problems with your current approach. It has been a while for me, but if I remember correctly, innerHTML and getElementById is not something that works perfectly across all browsers. That is why I suggest looking into jQuery.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am a newbie in javascript and java programming. I have a .java file with a function updateInfo(). I want to call that function in my .js file. How can I do that? Please help. Thanks!!!
Yes, you can, but not directly.
One option is to use a JAX-RS implementation like Apache CXF or Jersey. Once you have created a RESTful web service that maps to the method in your Java file, you can use JavaScript to make an AJAX call. Thus, you can certainly call a Java method via JavaScript in a form of a RESTful web service.
First make sure your java is compiled to jar (and extends applet / japplet)
You can invoke javascript functions with netscape.javascript.*
Example HTML
<head>
<title>Data Summary Applet Page - Java to JavaScript LiveConnect</title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
<script language="javascript">
var userName = "";
// returns number
function getAge() {
return 25;
}
// returns an object
function address() {
this.street = "1 Example Lane";
this.city = "Santa Clara";
this.state = "CA";
}
// returns an array
function getPhoneNums() {
return ["408-555-0100", "408-555-0102"];
}
function writeSummary(summary) {
summaryElem =
document.getElementById("summary");
summaryElem.innerHTML = summary;
}
</script>
<!-- ... -->
</head>
<body>
<script src =
"http://www.java.com/js/deployJava.js"></script>
<script>
<!-- ... -->
deployJava.runApplet(attributes, parameters, '1.6');
</script>
<!-- ... -->
<p id="summary"/> // this HTML element contains
// the summary
<!-- ... -->
</body>
Example java implementation:
package javatojs;
import java.applet.Applet;
import netscape.javascript.*; // add plugin.jar to classpath during compilation
public class DataSummaryApplet extends Applet {
public void start() {
try {
JSObject window = JSObject.getWindow(this);
String userName = "John Doe";
// set JavaScript variable
window.setMember("userName", userName);
// invoke JavaScript function
Number age = (Number) window.eval("getAge()");
// get a JavaScript object and retrieve its contents
JSObject address = (JSObject) window.eval("new address();");
String addressStr = (String) address.getMember("street") + ", " +
(String) address.getMember("city") + ", " +
(String) address.getMember("state");
// get an array from JavaScript and retrieve its contents
JSObject phoneNums = (JSObject) window.eval("getPhoneNums()");
String phoneNumStr = (String) phoneNums.getSlot(0) + ", " +
(String) phoneNums.getSlot(1);
// dynamically change HTML in page; write data summary
String summary = userName + " : " + age + " : " +
addressStr + " : " + phoneNumStr;
window.call("writeSummary", new Object[] {summary}) ;
} catch (JSException jse) {
jse.printStackTrace();
}
}
}
More information about invoking javascript from java
More information about invoking java methods from javascript
You can't directly call a java method from JavaScript. Equals whether the java Code is Compiled or not.
To bind Java code with JavaScript you must create first Applet. Only after, there are several techniques to invoke JavaScript from Applet and vice versa
I have a div where I load a Java applet, but the new version of Java is giving an unsigned certificate error:
I would like to know if I can restrict the loading of my Java applet (DeployJava.RunApplet), currently instantiated while the page is loaded, to only load when user clicks the View in 3D button?
Applet loading code:
<div id="appletContainer" runat="server" style="width:(document.body.clientWidth - 270);height:300" clientidmode="Static">
<script type="text/javascript">
var showCI = 0;
if (document.getElementById("hdnHas3D").value == "1" && !isAppleMobile()) {
var J3DStyleID = document.getElementById("hdn3DStyleID").value;
var code = "com.wirefusion.player.AppletPlayer";
var archiveList = "Some achive List";
var width = document.body.clientWidth - 270;
var height = 300;
var attributes = {
id: "appletContainerX",
name: J3DStyleID,
code: code,
codebase: ".",
width: width,
height: height,
mayscript: "true"
};
var parameters = {
progressFunc: "handleAppletProgress",
archive: archiveList,
java_arguments: "-Xmx200m",
regid: "6050-25",
resourcefolder: "/RichContent/3D_Vehicles/J3D/Vehicles/" + J3DStyleID + "/",
preloadfile: J3DStyleID + ".jar",
environmentType: "WEBSITE",
environmentWidth: width,
environmentHeight: height,
groupsXMLFile: "../../Resources/groups.xml",
vehicleXMLFile: J3DStyleID + ".xml"
};
var version = '1.6.0_20';
if (deployJava.versionCheck(version + '+')) {
docWriteWrapper(function () {
deployJava.runApplet(attributes, parameters, version);
});
} else {
if (document.getElementById("iframeContainer").style.display != "none") {
alert("Unable to load Interactive mode");
showCI = 1;
}
}
}
</script>
</div>
Don't include the regular <applet> (or <object>) tag in your HTML. Instead follow this tutorial on how to do dynamically add it to your page, using JavaScript.
HTML 4
function loadApplet(code,codebase,width,height,alt){
var placeholder=document.getElementById('placeholder');
if(window.opera){
placeholder.innerHTML='<applet code="'+code+'" codebase="'+codebase+'" width="'+width+'" height="'+height+'" alt="'+alt+'"></applet>';
}else{
var a=document.createElement('applet');
a.setAttribute('code',code);
a.setAttribute('codebase',codebase);
a.setAttribute('width',width);
a.setAttribute('height',height);
a.setAttribute('alt',alt);
placeholder.appendChild(a);
}
}
HTML 5
function loadApplet(code,codebase,width,height,alt){
var placeholder=document.getElementById('placeholder');
var a = document.createElement('object');
a.setAttribute('type','application/x-java-applet');
a.setAttribute('width',width);
a.setAttribute('height',height);
a.setAttribute('alt',alt);
var codeParam = document.createElement('param');
codeParam.setAttribute('name','code');
codeParam.setAttribute('value',code);
a.appendChild(codeParam);
var codebaseParam = document.createElement('param');
codebaseParam.setAttribute('name','codebase');
codebaseParam.setAttribute('value',codebase);
a.appendChild(codebaseParam);
placeholder.appendChild(a);
}
In your HTML create a placeholder DIV, i.e. where you want to it to be loaded into, and a link to load your applet. You will need to customise the values in the load link to your values of the Applet.
<div id="placeholder"></div>
<input type="button" value="Load Applet" onclick="loadApplet('TestApplet.class','.','200','300','demo applet')" />
The linked tutorial explains more about how to make it pretty. The code above is just simply the concept.
Update since modification of question
Your code appears to load the applet using JavaScript already. The problem is the script is being run as soon as the page is loaded and not when the user clicks on the View in 3D button.
To prevent it running immediately, you can wrap the loader code in a function called loadApplet. So explained in pseudo code:
function loadApplet() {
// Your existing applet loading code
}
So using your included source code, I have wrapped it with a function, which will prevent it running when your page is loaded.
<div id="appletContainer" runat="server" style="width:(document.body.clientWidth - 270);height:300" clientidmode="Static">
<script type="text/javascript">
// Wrap your code with a function called loadApplet
function loadApplet() {
// Your applet loading code:
var showCI = 0;
if (document.getElementById("hdnHas3D").value == "1" && !isAppleMobile()) {
var J3DStyleID = document.getElementById("hdn3DStyleID").value;
var code = "com.wirefusion.player.AppletPlayer";
var archiveList = "Some achive List";
var width = document.body.clientWidth - 270;
var height = 300;
var attributes = {
id: "appletContainerX",
name: J3DStyleID,
code: code,
codebase: ".",
width: width,
height: height,
mayscript: "true"
};
var parameters = {
progressFunc: "handleAppletProgress",
archive: archiveList,
java_arguments: "-Xmx200m",
regid: "6050-25",
resourcefolder: "/RichContent/3D_Vehicles/J3D/Vehicles/" + J3DStyleID + "/",
preloadfile: J3DStyleID + ".jar",
environmentType: "WEBSITE",
environmentWidth: width,
environmentHeight: height,
groupsXMLFile: "../../Resources/groups.xml",
vehicleXMLFile: J3DStyleID + ".xml"
};
var version = '1.6.0_20';
if (deployJava.versionCheck(version + '+')) {
docWriteWrapper(function () {
deployJava.runApplet(attributes, parameters, version);
});
} else {
if (document.getElementById("iframeContainer").style.display != "none") {
alert("Unable to load Interactive mode");
showCI = 1;
}
}
}
}
</script>
</div>
Then to your View in 3D element you must add an onclick attribute calling the loadApplet() function. For example:
<input type="button" value="Show in 3D" onclick="loadApplet()" />
Note: It may be the case that your View in 3D button already has an onclick attribute wired to a function that brings your applet into view, in which case you would still want this to be called after your load function. I have used showApplet() as an example, this is most likely different for you.
<input type="button" value="Show in 3D" onclick="loadApplet(); showApplet();" />
If you provide the code for your Show in 3D button, I can better assist you here.
looking for a javascript class like swfobject to embed java and have a simple fallback if the user doesn't have java or refuses the security prompt.
thanks,
Josh
You could build one pretty easily.
Have something like a div set up like this:
<div id="java-applet">
Message to user saying that they need Java here
</div>
Then add Java Plugin Detection (builder) to your JavaScript. Then if that returns true, then do something like:
document.getElementById("java-applet").innerHTML = "<applet>stuff here</applet>";
appletobject may work, but I have not used it.
Just embed the applet like you normally do and insert the fallback inside or insert a javascript snippet to remove the object: Besides param, you can add other elements, e.g. paragraphs with text or javascript calling some function to replace the object.
<script type="text/javascript">
function replace_object(x) {
$(x)...
}
</script>
<object x="y" id="some_applet">
<param name="y" value="z">
<p>java not available. some alternative here. <!-- option 1 --></p>
<script type="text/javascript">
replace_object('some_applet'); // option 2
</script>
</object>
This helps!
I got a very strange problem while using applet to do batch file downloading from the server side.
The Ajax request seems conflict with applet request, the applet file downloading interrupted with some socket exception.
The applet works fine under JRE5.0, it might be caused by our recent upgrade to JRE6.0.
<div id="java-applet"></div>
<script>
var t;
function startApplet() {
var attributes = {codebase:'<%=request.getContextPath()%>',
code:'<%=appletClass%>',
archive:'applet/SignedApplet.jar',
width:0,
height:0} ;
var parameters = {para1:'value1',
para2:'value2',
java_arguments:'-Xms64m -Xmx512m'
} ;
var version = '1.6' ;
var buildAppletTag = function() {
var tag = '<applet';
for (var attribute in attributes){
tag += (' ' + attribute + '="' + attributes[attribute] + '"');
}
tag += ">";
for (var parameter in parameters){
tag += '<param name="' + parameter + '" value="' + parameters[parameter] + '"/>';
}
tag += '</applet>';
return tag;
};
document.getElementById("java-applet").innerHTML = buildAppletTag(attributes, parameters, version);
clearTimeout(t);
}
t = setTimeout("startApplet()", 1000); // delayed
</script>