How to get value to dropdown from database using ajax? - java

I have dropdown with some optional value.if change the those value based on that will display another dropdown with value from database.I am doing this process in jsp page.First dropdown values are static(coded in jsp).but second dropdown values are come from database when changeevent of first dropdown.
Here i need to implement ajax or javascript ? Could you give me examples of this drop down.

You can do it with JQuery and Ajax pretty easily. Check out
http://www.chazzuka.com/experiments/jquery-dropdown/
for an example

Here i need to implement ajax or
javascript ?
Ajax.
Could you give me examples of this drop down.
JQuery works fine. I found DWR framework to be easier to understand for newcomers to Ajax. You can look at tutorials on that here.

You have two drop down
<select id="first" onchange="get_result();" >
somevale
</select>
<select name="second" >
</select>
now you need to give body to our get_result function
function get_result()
{
var value = $("#id).val();
JQuery.ajax("some_url",{ id : value }, function(){} )
}
This way you can do this. You specific check JQuery tutorial.

Related

jquery datatables not working on JSF

How can I apply jquery datatable on JSF datatables ?
The following not working , because id on jsf datatable (i.e <h:datatable id="example"...) becomes j_idt6:example on html.
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#example').dataTable();
} );
</script>
any solution ?
Note: I am using because of client pagination and search.
Change
<h:datatable id="example"...
to
<h:datatable styleClass="example"...
Then just use $('.example').dataTable();
you may wrap the table into the form, and then the id fill be formID:tableID
Since you are working with JSF, you should consider using the PrimeFaces Library , they got a really great table component
If you still want to go with the really great datatables plugin here are several solutions:
1) Add prependId="false" to your h:form , that way you wont get that id with form prefix
2) Set an id to your h:form and use the following jquery code $('#myForm\\:example').dataTable();
3) Call the dataTable constructor on styleClass="example" attribute of the table instead of the id
Also, you can try out my Yet Another DataTables Column Filter (Yadcf)

Calling a backend Java method from JavaScript/jQuery in JSP

I have a JSP in which there is a select list containing entity kind names. When I select an entity kind I need to populate another select list with the field names of the selected entity kind. For that I call a JavaScript function on the onchange event.
In the JavaScript method I need to call a method in the backend that returns an arraylist that contains the field names of the selected entity kind.
How do I call the method with and without Ajax? Also how do I populate the second select list dynamically with the arrayList?
I'll describe two ways to go: with/without AJAX.
If you want to do a synchronous form submit you'll need to attach onchange event to your first select element:
<select name="select-one" id="select-one" onchange="this.form.submit()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
When done this way, the form will be submitted and first select option will be available as request.getParameter("select-one"), based on which you'll provide data for second dropdown population, typically forwarding to a JSP.
If you want to retrieve a list via AJAX and repopulate another dropdown, you can send an AJAX request and handle returned data in a callback function:
var val = $('#select-one option:selected').val();
$.ajax({
url: "servletURL",//servlet URL that gets first option as parameter and returns JSON of to-be-populated options
type: "POST",//request type, can be GET
cache: false,//do not cache returned data
data: {one : val},//data to be sent to the server
dataType: "json"//type of data returned
}).done(function(data) {
var second = $("#select-two");
$.each(data, function() {
options.append($("<option />").val(this.value).text(this.label));
});
});
When done this way, the second dropdown will be repopulated without page refresh.
Write a JavaScript function names callAJAX on the onchage event of your select drop down
In your callAJAX function , make an ajax call to the back end, get the response from the server, and populate the new drop down with the response coming in your ajax call
I hope you can make ajax calls , if not let me know.
You want to load your list dynamically from backend. You must communicate with your server either:
with a page load (form submit)
or without a page load(ajax).
If AJAX is not your requirement, I suggest you do it by form submit(with page load) first because it's simple and easier for beginner.
Agree with Jai. You will have to submit that form to the java method, then your java method will return the arrayList. Of course if you form submit, your page will be refreshed and I'm not sure if your previously selected values will still be selected on the form. I'm not too clued up with this method of doing it. I prefer to use jquery.
With jquery you can do it like this:
$.ajax({
url: "/MyApp/MyClass/getArrayList",
type: "GET",
data: "selectedEntity=" + s_entity,
success: function(response){
//handle returned arrayList
},
error: function(e){
//handle error
}
});
Put this in a function. Pass your selected entity as a parameter and handle the response in the success part. Of course your java method should map 'selectedEntity' to a parameter in the method header. In Spring it's done like this:
private #ResponseBody ArrayList getArrayList(#RequestParam("selectedEntity") String entity)

Communicating between JavaScript and Servlet

In my JSP page I have DIV.
<div id="100">
ALI
</div>
When I click on this DIV...
$("#100").click(function(){
});
...I need to send the value of the id 100, to a servlet, so that the servlet makes some database java codes, and returns for example, either 1 or 0. How can I do that? and is this the proper way?
Using Ajax, you should call your server using a URL similar to this:
http://localhot:8080/youAppContext/yourServer?id=100
Then, in the servler side, you should retrieve the value that will be in the request with the name "id"
There are out there many tool as jQuery that can help you to do the Ajax petition.
Edited
Well, here you can find a very simple Ajax example using jQuery. In the example, instead call a file (test1.txt) you should invoke a URL (as I described above). Of course, you will need to write some JS code to build your URL (where id be a variable). Once task is done in servlet side, you can return whatever, for example: "done" and display or not this information the HTML as it is done in the example.
Take a look to this Web, there are many links that can help you.
get the value using
var value = $("#100").html();
and pass it to servlet using AJAX

How to send selected objects parameters from drop down menu to a function in JSP

I have a drop down menu which fills with some doc names. Now when a person selects a document it calls onDocumentChange() method.
To fill the drop down menu i receive a object called result which is a list of doc objects from server.
<select id="documentSelect" onChange="onDocumentChange()">
<c:forEach items="${results}" var="result">
<option id="${result.getDocDisplayURL()}"><c:out value="${result.getDocFn()}"/></option>
</c:forEach>
</select>
Till this point it is strainght forward.
Now this doc object has some other attributes called date and time. Now when the user clicks any item from drop down menu i want to send that particular items time and date attributes to onDocumentChange() method. How can i do that.
I am guessing something like this
<select id="documentSelect" onChange="**onDocumentChange(result.date, result.time)**">
<c:forEach items="${results}" var="result">
<option id="${result.getDoc()}"><c:out value="${result.getText()}"/></option>
</c:forEach>
</select>
Thanks
You seem to be thinking that JavaScript runs together with Java/JSP. This is untrue. Java/JSP produces HTML and JavaScript is part of that HTML and works on the HTML DOM tree only. You need to make sure that your Java/JSP code produces HTML code containing exactly the information JavaScript needs to access. You can let Java/JSP print those variables as an attribute of a HTML element, like <option> in your case. You can use custom data-* attributes in HTML to append custom attributes.
<option value="${result.doc}" data-date="${result.date}" data-time="${result.time}">
You can get the currently selected <option> element in JavaScript as follows
var option = select.options[select.selectedIndex];
var doc = option.value;
var date = option.getAttribute("data-date");
var time = option.getAttribute("data-time");
// ...
You only need to change the onchange handler to pass the HTML <select> element itself
onchange="onDocumentChange(this)"
with
function onDocumentChange(select) {
// ...
}
By the way, why are you using separate properties for date and time instead of a single java.util.Date property? There's something wrong in the model design.

How to access a Java object in JavaScript from JSP [duplicate]

This question already has answers here:
Access Java / Servlet / JSP / JSTL / EL variables in JavaScript
(5 answers)
Closed 5 years ago.
I have a dropdown box in JSP, listing a Java object (accessing the object through the MVC controller's addAttribute). Now, on selection of an option from the dropdown box, I would like to display the selected employee's other details (example - ${employee.employeeCV}, ${employee.employeeName}) in a div. I have a JavaScript function for that (displayCV()). But I am not sure how to do this.
JSP -
<c:forEach items="${employees}" var="employee">
<option value="${employee.id}" onclick="displayCV();">
${employee.employeeName}
</option>
</c:forEach>
<b>CV:</b>
JavaScript
function displayCV() {
var valueSelected = $('#employeeList').val();
var div = $('#candidateDiv');
}
How can I do this?
You can't access Java classes directly from JavaScript. You have to use some kind of web service communication between the JavaScript (client) and Java (server). You can make use of the onchange event which will send a request to the server to return XML/JSON which you can parse to get the data (I see you're using jQuery, and it has parseJSON method already) and update the corresponding node in the DOM.
Another easier way, though, that is not multi-user friendly (because it can't detect updates) is to "convert" the Java object to JavaScript and update the data using that object (still using onchange). Something like:
// This is JavaScript code written in the JSP
var employees = {
<c:forEach items="${employees}" var="employee">
"${employee.id}": {
name:"${employee.employeeName}",
cv:"${employee.employeeCV}",
},
</c:forEach>
}
Now when JSP parses this, it would generate, for instance:
var employees = {
"1": {
name:"foo",
cv:"cv1",
},
"2": {
name:"bar",
cv:"cv2",
},
}
Meta of what LeleDumbo said here already:
First, you must understand that JSP is a server-side view technology, whereas JavaScript typically runs on the client (browser).
Now, how you solve the problem in hand. So, you can make an Ajax request from your JavaScript code, which will fetch you the data in JSON/XML format. Then, you can present that data in the browser using JavaScript.
Further reading: jQuery Ajax API and code samnple snippets
Call the function on the onchange event of select instead of onclick of options. And use:
document.getElementById('GrdDamagedstock_tplRowEdit_ctl00_cmbFromBin').options[ele.options.selectedIndex].innerHTML;
to get the selected value.

Categories

Resources