Ajax how can I refresh a drop down after call servlet - java

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()).

Related

in spring framework how to get response from controller to jsp page by ajax call passing an id value to controller

In my program i need to perform an operation by passing id.The id is selected from a dropdown box(ie;changing dynamically).so to pass the id i'am using ajax.but i don't know the code to receive the response back from controller in spring.
<div class="form-group">
<label class="col-sm-4 control-label">Employee</label>
<div class="col-sm-6">
<select id="empId" name="empId" class="form-control" >
<option value="" >--Select--</option>
<c:forEach var="row" items="${employeeList}" >
<option value="${employeeList.Id}">${employeeList.name</option>
</c:forEach>
</select>
</div>
<div class="col-sm-6">
<input type="text" name="empname" id="empname" class="form-control"/>
</div>
</div>
//i need to pass the employee id from the dropdown box to controller and get //the name of the employee as response .and set the response value in the text //box.how can be it done in spring using ajax.
//ajax code i tried
$('#empId').change(function(event) {
var eId= $("select#empId").val();
$.get('getEmpName', {
id: eId
}, function(data) {
$('#empname').val(data);
});
});
//but i am not getting any response ie:nothing in data
Here the ajax side code:
$('#empId').change(function() {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'your_url', // in your controller side (RequestMapping value)
data: 'empId='+$('#empId').val(),
success: function(responseData, textStatus) {
// your stuff here. you found the response in responseData var.
},
complete: function(textStatus) {
},
error: function(responseData)
{
}
});
});
And your controller side code like something below,
#RequestMapping(value = "your_url", method = RequestMethod.POST)
public ResponseEntity<String> postMethod(HttpServletRequest req) {
String jsonString = "";
String empId = req.getParameter("empId");
// your operation done here and
//convert it to json format before sending response.
jsonString = gson.toJson("your response convert here to json format"); // here i used google Gson library to convert your response in json format.
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "text/html; charset=utf-8");
return new ResponseEntity<String>(jsonString, responseHeaders, HttpStatus.CREATED);
}

passing servlet values to jsp page

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.

JSP not calling ajax function

I have written an ajax function which will be called when someone selects a year from a dropdown. On selecting the year, the ajax will call a servlet based on passed URL and that servlet will set a value in properties file. However, the problem is, on selecting the year, my ajax block is not called
</tr>
<tr>
<td>Year</td>
<td>
<html:select property="yearId" >
<html:options collection=
"<%=GlobalValues.LIST_MODELYEAR%>"
property="id" labelProperty="value" />
</html:select>
(Required)
</td>
</tr>
<script>
$(document).ready(function()
{
$("#yearId").change(function()
{
var selectedValue = $(this).find(":selected").val();
$.ajax
({
url : "/ModelByYear.do?cID="+selectedValue+'',
});
});
});
</script>
Maybe you can check the url you build first before calling the AJAX?
$(document).ready(function()
{
$("#yearId").change(function()
{
var selectedValue = $(this).find(":selected").val();
window.location = "/ModelByYear.do?cID="+selectedValue;
});
});
Remove the / from your URL as given below and the , is not neccesory
$.ajax({
url : "ModelByYear.do?cID="+selectedValue
});
Try by using the below code
$.ajax({
type: "GET",
url: "ModelByYear.do",
data: {cID:selectedValue},
success: function(result){
alert('Result: ' + result);
},
error: function(err){
alert('Error: ' + e);
}
});
type is html request type you can use GET or POST
ModelByYear.do is URL in you case you must map this url-pattern in WEB.xml
While working on JSP's don't call jsp pages directly instead configure in WEB.xml as given here

JSP form values passed to a servlet

I have a form in JSP in the following manner :
<form id="provision-field" method="post" action="${pageContext.request.contextPath}/myServlet">
<fieldset>
<ol class="fields">
<li>
<label for="field1">field1</label>
<input type="text" id="field1" "
value="<%= field1 %>"
/>
<span class="description">
<span class="optional">Optional</span>
</span>
</li>
</ol>
</fieldset>
<div class="actions">
<button type="submit" name="Submit">
Submit form
</button>
Cancel
</div>
</form>
I have a js snippet on click of the submit button does the following
var field = document.getElementById("field1").value;
$.ajax({
url: '${pageContext.request.contextPath}/myServlet'
type: 'POST',
data: field,
dataType: "html",
success: function(html) {
alert("Success");
},
error: function(error){
alert("ERROR");
}
});
When I just use the form element (ie take out the js code) , I can reach my servlet but none of my form parameters are passed . when I try using the js code , the ajax request does not work . could someone point to me how this should be correctly done .
The servlet code is :
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.info("Inside the post function");
logger.info(request.getParameter("data");
}
var field = document.getElementById("field1").value;
$.ajax({
url: '${pageContext.request.contextPath}/myServlet'
type: 'POST',
data: {
data :field
},
dataType: "html",
success: function(html) {
alert("Success");
},
error: function(error){
alert("ERROR");
}
});
Inside servelt following code in doPost method :
Assuming that you have primary knowledge of HttpServlet...
request.getParameter("data");
I am sharing small Ajax with Servlet tutorial , which may help you for further problem... Download Link- AJAX Servlet Tutorial
data: { field1:field1Value } send like this
and then access request.getParameter("field1"); in servlet
As form submission method is post method="post", you need to make sure you are fetching request values in doPost(request, response) method

Call java method from javascript

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.

Categories