I am trying to get values to a drop down list based on the previous value selected from another drop down list. I am able to call to java class from the servlet and the values are returned to servlet but it is not getting passed down to jsp page
jsp page part(index.jsp)
<select id="region" name="region" class="form-control" onchange="getgroups()" required="required" >
<option value="" default selected>Select region</option>
<option value="region1">region1</option>
<option value="region2">region2</option>
<option value="region3">region3</option>
<option value="region4">region4</option></select>
The onchange value in region calls this function
function getgroups(){
var j = document.getElementById("region");
var s = document.getElementById("secret_key");
var a = document.getElementById("access_key");
var output = $.ajax({
type: 'POST',
url: 'http://localhost:8066/VMMigratorNew/ec2util',
data: {"region":j.value,
"secret_key":s.value,
"access_key":a.value,
},
success: function(response) {
return output.responseText;
}
});
}
and in servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String region = request.getParameter("region");
String secretKey = request.getParameter("secret_key");
String accessKey = request.getParameter("access_key");
List<String> vpcs = RunEc2Command.getVPCForUSer(AWS_ACCESS_KEY, AWS_SECRET_KEY, region);
if(vpcs != null && vpcs.size() > 0) {
request.setAttribute("vpclist", vpcs);
}
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
}
and in the same index.jsp page , I am trying to show the list values in a drop down box which is in index.jsp itself.
<select id="vpc" name="vpc" class="form-control" placeholder="Choose VPC" >
<option value="" default selected>Select VPC</option>
<c:forEach items="${vpclist}" var="vpcs">
<option>
${vpcs}
</option>
</c:forEach>
</select>
I need to get the value of VPC in drop dron box after selecting the value from region drop down box. Thanks for the help in advance.
Currently, the workflow in your servlet is suitable for a synchronous request, which requires the servlet to return the whole HTML in the HTTP response for the browser to render. However, it seems to me that your intent is instead of querying the servlet in order to obtain a VPC list, and you are trying to pose the query asynchronously using AJAX.
Hence, my suggestion would be to let the servlet return the VPC list in some format (e.g., JSON). In the success callback, you should modify the DOM in order to insert the list you received.
Related
I'm working on a project and I'm trying to do a cascade dropdown using ajax.
I managed to do the implementation but I don't know how to pass the selected id from the second dropdown to a controller using thymeleaf in order to show the information about the selected airport.
So, this is the script:
function retrieveAirports() {
$.ajax({
url: '/countries/airports?countryId=' + $('#countrySelect option:selected').val(),
type: 'get',
contentType: 'application/json',
success: function (result) {
var $dropdown = $("#airportSelect");
var $id = $("#airportId");
$dropdown.empty();
$.each(result, function() {
$dropdown.append($("<option/>").val(this.id).text(this.name));
});
},
error: function () {
// what do you want to do in case of error
}
});
}
And this is the implementation of the dropdown. First, we have the country dropdown
<select id="countrySelect" onchange="retrieveAirports()">
<option selected value="-1"></option>
<option th:each="country : ${countries}" th:value="${country.id}" th:text="${country.name}">Option</option>
</select>
And this one is the airport dropdown, the result of this one depends on the id that was passed from the first one to the script.
<form th:action="#{/airport}" method="post" th:object="${airportSelect}">
<select id="airportSelect">
<option selected value="-1"></option>
</select>
<input type="submit" value="Send"/>
</form>
Can someone please help me?
Thank you!
Add a name to the airport selector, for example airport:
<form th:action="#{/airport}" method="post" th:object="${airportSelect}">
<select id="airportSelect" name="airport">
<option selected value="-1"></option>
</select>
<input type="submit" value="Send"/>
</form>
And then, when you click the submit button, the Spring controller for the path /airport will be called with airport as a POST parameter. For example:
#Controller
public class AirportController {
#PostMapping("/airport")
public View viewAirport(#RequestParam("airport") int airport) {
// ...
}
}
I have the following jsp
<c:forEach items="${vlocomotoras}" var="vl" varStatus="i">
<select class="regimenFrenoLocomotora" id="regimenFrenoLocomotora" name="regimenFrenoLocomotora" onchange="calcularDocumentoTren();">
<option value="P" ${"P" == v1.regimenFrenoLocomotoras ? 'selected="selected"' : ''}>P</option>
<option value="G" ${"G" == v1.regimenFrenoLocomotoras ? 'selected="selected"' : ''}>G</option>
</select>
</c:forEach>
I have the following ajax post to a servlet
$.ajax({
type: "POST",
url: "/copernico/SrvRenfeSituacion",
data: {
"arrayLocomotora[]" : arrayLocomotora,
todo:todo,
fecha:fecha,
tren:tren
},
error:function(){
console.log("ERROR");
},
success:function(responseText){
alert('responseText ');
alert(responseText);
alert("Success");
}
});
This is the servlet
req.setAttribute("vlocomotoras", locomotoras);
Now I want to refresh the drop down with the new values of vlocomotoras. How can I do this?
Have your servlet return a json array with the data you need. See this question for doing that.
(In the ajax call, set dataType="json" for the call to expect a json object as response)
Once you get the json object in the ajax response, you can replace the OPTION tags inside the SELECT using jQuery (empty() and appendTo()).
I'm trying to get the value of the selected item in JSP page, when I'm trying it locally it works! but once I published it, it stopped working because it always returns "null" value for the parameter
JSP/JSTL code:
<form action ="SelectedEntity" method ="get">
<label>Please select one of the following entities: </label>
<select name="Entity">
<c:forEach var = "entity" items ="${entities}">
<option ><c:out value="${entity}"/></option>
</c:forEach>
<input type = "submit" name = "submit" id = "submit" value ="Go">
</select>
</form>
and this is the servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String entity = request.getParameter("Entity");
This is always returning null .. can someone help me with that?
I have a web jsp web application. In one page I need two dropdownlist. When I will select a value from dd1 then second dropdown will be fill according this value. How I can call java function from dropdown 1 change event in javascript or jQuery?
I got example but that is calling jsp page but I need to java method and send parameter what i got from dropdown1
This is my dropdown dd1. So if I select tom I have to related information of tom in dd2.
<td>
<select id="dd1">
<option value="1">john</option>
<option value="2">Tom</option>
</select>
</td>
</tr>
<tr>
<th> Projects </th>
<td>
<select id="dd2">
<option value="1">pp1</option>
<option value="2">pp2</option>
</select>
</td>
I have following code
$(function () {
var ddVal = '';
var dropdown = document.getElementById("dd1")
$(dropdown).focus(function () {
ddVal = $(this).val();
}).blur(function () {
if (ddVal == $(this).val()) {
$(this).change();
}
}).change (function () {
});
For change event of dd1. But I don't know how to call java method from jQuery.
In my application I have a java class where there is a method which return list that I need to load in dd2 dropdown.
Can anyone help me regarding this issue?
You should do such things with AJAX.
JavaScript sends the request, your controller utilizes the Java part to carry out what's needed and then passes back a JSON response, based on which your JavaScript manipulates the page.
EDIT:
For example, the script can issue the following request:
$.ajax({
"type": "POST",
"url": "/ajaxAPI/updatedropdown/",
"data": {
"selected": selectedMenuItemId
},
"success": function (data) {
var menuItems = data.menuItems;
dropDownToChange.updateChoices(menuItems);
}
});
Your controller for such a request might look like:
public class DropDownListController implements Controller {
#Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
MenuItem selected = extractSelectionFromRequest(request);
List<MenuItem> choices = dropDownListService.getMenuFor(selected);
ModelAndView mav = new ModelAndView("dropDownListAjax.jsp");
mav.addObject("menu", choices);
}
// WARNING! Some error checks are missing!
private MenuItem extractSelectionFromRequeset(HttpServletRequest request) {
validateRequest(request);
return dropDownListService.getMenuItemById(request.getAttribute("selected"));
}
// ...
}
And for the view you could have something like:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
{
"menuItems": [
<c:forEach items="${menu}" var="menuItem">
{
"url": <c:out value="${menuItem['url']}"/>,
"caption": <c:out value="${menuItem['caption']}"/>
},
</c:forEach>
]
}
The client side JavaScript will then receive a response like:
{
"menuItems": [
{
"url": "http://www.example.com/"
"caption": "Home"
},
{
"url": "http://www.example.com/news/list/"
"caption": "News"
},
{
"url": "http://www.example.com/forum/topics/"
"caption": "Forum"
},
]
}
Please note that the above example might not be 100% correct as there have been a while since I last used JSP (and I'm more comfortable with FreeMarker anyways).
Basically, you invoke part of your web infrastructure that, rather than responding with HTML code, passes back JavaScript Objects based on the results of the requested operation.
Since jQuery is in the client side and JSP is on the server side, you don't have the option of directly calling the remote method. The standard way to do this in the world of the Web is AJAX.
I am trying to populate city, country and statelist using ajax, and servlets.
Now I know how to get the XMLhttpRequest object. There is a standard mechanism to do that and depending on the cross browser compatibility, you do get a ActiveX or a xml object..
Then you send a request to the actionservlet, using xmlhttprequest.open() and you send the request and you have an event handler function to take care of onreadystatechange issue, Now, when it comes to receiving the response, I get an error stating that the response is not completely received, i.e the status != 4... now.
I was wondering, how does the entire mechanism work..
how to put the parameters in the request, send it to servlet, and then I know how to retreieve the param from the URL.. but then how to send a valid response...??
I am confused on the ajax part, because I am not using / not use PHP. It is harder to think. Please suggest what should be done.
Is there any easier way to populate a city, country and state list??
Just let the servlet return the desired dropdown options in the desired format based on the request parameters in the doGet() method. Here's an example which returns it in JSON format with help of Google Gson:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String type = request.getParameter("type"); // Returns "country" or "state".
String value = request.getParameter("value"); // Value of selected country or state.
Map<String, String> options = optionDAO.find(type, id); // Do your thing to obtain them from DB. Map key is option value and map value is option label.
String json = new Gson().toJson(options); // Convert Java object to JSON string.
response.setContentType("application/json"); // Inform client that you're returning JSON.
response.setCharacterEncoding("UTF-8"); // Important if you want world domination.
response.getWriter().write(json); // Write JSON string to response.
}
Assuming that the above servlet is mapped on an url-pattern of /options, you could use it as in the following JSP example with help of jQuery. I am recommending jQuery because you would otherwise end up with 10 times as much JavaScript code needed for this "simple" task.
<%# page pageEncoding="UTF-8" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 3983929</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$('#country').change(function() { fillOptions('state'); });
$('#state').change(function() { fillOptions('city'); });
});
function fillOptions(dropdownId) {
var dropdown = $('#' + dropdownId);
$.getJSON('options?type=' + dropdownId + '&value=' + $(this).val(), function(opts) {
$('>option', dropdown).remove(); // Clean old options first.
if (opts) {
$.each(opts, function(key, value) {
dropdown.append($('<option/>').val(key).text(value));
});
} else {
dropdown.append($('<option/>').text('Please select ' + dropdownId));
}
});
}
</script>
</head>
<body>
<form>
<select id="country" name="country">
<c:forEach items="${countries}" var="country">
<option value="${country.key}" ${param.country == option.key ? 'selected' : ''}>${country.value}</option>
</c:forEach>
</select>
<select id="state" name="state">
<option>Please select country</option>
</select>
<select id="city" name="city">
<option>Please select state</option>
</select>
</form>
</body>
</html>
Here I am assuming that you've already prepopulated the ${countries} as being a Map<String, String> in a servlet which has preprocessed the request to this JSP for the initial display.