Call java method from javascript - java

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.

Related

Ajax how can I refresh a drop down after call servlet

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

Load data from html form, update database and display data on the same page in table using java servlet

I need some help.
I have a small application which consists of Java Servlet and html form.
User puts some data in a html form and after clicking on submit button the java servlet gets the data in it's post method (loads it in a database). Till now all works fine. I am using java servlet and tomcat.
What I want to do now is to display the data in a table on the same page on html. I have found, that this would be possible through ajax get method. But somehow I can't get it right.
Here simplified code of my application:
Java Servlet:
#WebServlet(name = "MyServlet", urlPatterns = { "/MyServlet" })
public class MyServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
// getting the values submitted by the user from the html form
String name = request.getParameter("name");
String surname = request.getParameter("surname");
// here goes some logic to load data in the database
// data from database is recieved as an array and is then converted to
// json
// here I can only print the whole json retrieved from DB
// and it is displayed on another page with myurl/MyServlet
response.setContentType("application/json");
PrintWriter out = response.getWriter();
response.setCharacterEncoding("UTF-8");
out.println(json);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
// nothing happens here
}
In my html form I have the following (the most important things here only):
<form action="MyServlet" method="post">
<input class="form-control" type="text" name="name" id="name">
<input class="form-control" type="text" name="surname" id="surname">
<input type="submit" class="btn btn-info" id="MyS"value="MyServlet">
<table class="table" id="table">
<tr>
<th>name</th>
<th>surname</th>
</tr>
The user input is stored in a database and everything is working fine.
The problem is, that I get no response and I would like to display all of the data given from user in a table, which schould be updated after each submit and user schould stay on the same page (don't actually know, how to do this).
From the database I get an Array which I can convert to JSON and all this information schould be displayed in a table.
I tried to write some ajax.get like this (I am a real newby in javascript):
<script>
<script type="text/javascript">
$("#MyS").click(function() {
}
$.ajax({
url: "/MyServlet",
type: "POST",
dataType: '{json: json}',
data: myvalue,
success: function(data) {
$('#table').append(data);
},
});
</script>
But no data is displayed in the table or somewhere.
I would be glad to get some hints i what I am doing wrong and how should it be done properly?
Thanks in advance.
Execute it with these lines and tell me what response you get in your browser's console:
$.ajax({
url: "/MyServlet",
type: "POST",
dataType: '{json: json}',
data: myvalue,
success: function(data)
{
console.log( data ); // logs this on success
$('#table').append(data);
},
**error: function (textStatus, errorThrown)
{
console.log( textStatus ); // log this on error
console.log( errorThrown );
}**
});

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.

JQuery - Ajax - Struts2 list

Im looking for a little help on getting my JQuery/Ajax call to return a List from a Struts action and populate a DIV with the list elements using s:iterator.
I have the following JQuery
function lookupCustomerJs() {
alert("lets start");
$.ajax({
type: "POST",
url: "lookupCustomerAjax",
data: $('#lookupCustomer').serialize(),
success:function(response) {
alert("do stuff");
$('div#custList').replaceWith($(response).find("div#custList"));
},
failure:function(response) {
alert('Ajax call failed');
},
error:function(response) {
alert(exception);
}
});
}
I have a DIV within my page which I then want to iterate the list through
<div id="custList">
<s:iterator status="stat" value="customerList" var="customer">
<s:param name="custFName" value="%{customer.firstname}" />
</s:iterator>
</div>
And my Action method which IS called, because when I debug, the debugger goes through the code.
private List<Customer> customerList;
public String lookupCustomerAjax() {
dummyData();
return SUCCESS;
}
This successully calls my Action method, but all I get is the "lets start" alert, then nothing else, no errors, nothing!
So I'm guessing it's just the jQuery/Ajax success:function(response) { not fireing correctly, but can't see why.
It is probably the "lookupCustomerAjax" is an invalid url or file name. You should try adding the extension.
Also, for troubleshooting, you should console.log(response) in your succession to see that you are actually get the result.

ajax + servlet country state city list

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.

Categories