Return a list using JQuery - java

I am using the following JQuery, JSP and Controller to return list of cities upon changing the country drop down menu on my app JSP page, yet I think the dataType, success parameters in the JQuery are not correct as I am not getting back the list. So can someone please tell me what I am doing wrong here and how I can get the list of Cities to add them to the cities drop down menu upon changing the Country drop down menu?
Thanks for your time
<script type="text/javascript">
function loadCity(){
var countryData="countryId="+$(country).val();
$.ajax({
type: "POST",
url: "LoadCities.htm",
data:countryData,
dataType: "javascript",
success: function(cities){
loadCities(eval(cities))
}
});
}
function loadCities(citiesLst){
clearCitiesDD();
for(var i=0;i<citiesLst.length;i++){
var city=citiesLst[i];
appendCity(city.id,city.value);
}
}
function clearCitiesDD(){
$('#cityDD').find('option').remove();
}
function appendCity(id,cityName){
$('#cityDD').append($("<option id='"+id+"'>" + cityName + "</option>"));
}
}
</script>
and in my application controller I have the following code:
#RequestMapping(value = "/LoadCities.htm", method = RequestMethod.GET)
public #ResponseBody
List<City> getCityByCountryID(HttpServletRequest request, HttpServletResponse response)
throws Exception {
List<City> list=
icitys.getCitiesByCountry(Long.parseLong(request.getParameter("countryID")));
return list;
}
and in the JSP file I have the following City and country drop down menus:
<tr>
<td align="right">Country</td>
<td align="left">
<select id ="country" name="country" onchange="loadCity()">
<option value="0">--select--</option>
<c:forEach var="countrylst" items="${countriesList}">
<option value="${countrylst.id}">${countrylst.countryName}</option>
</c:forEach>
</select>
</td>
</tr>
<tr>
<td align="right">City</td>
<td align="left">
<select id="cityDD" name="cityDD">
<option value="0">--select--</option>
</select>
</td>
</tr>

Hope you got solution after changing $(country) to $('#country').
One more thing, you put dataType as "javascript" but avail data types are xml, json, script, or html.
Better try with html.
Good luck.

Should
var countryData="countryId="+$(country).val();
not be
var countryData="countryId="+$('#country').val();

Related

MVC Spring Controller, display dbData in HTML file

If I write a Spring MVC Controller, how can I display the DBData in my HTML file.
e.g. I have db.table called Setting and I want to display the IDs from that table in my HTML file as a Dropdown list.
#Controller
public class CustomChannelController {
private Setting setting;
private Diagram diagram;
private Channel channel;
#RequestMapping(value = "/customchannel", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
public #ResponseBody Setting getId() {
return this.setting;
}
<table>
<tr>
<td>
<label class="col-md-12 control-label"> <%=language['UI.reportSetting.channel']%> : </label>
</td>
<td>
<select id="selectReportChannel" class="form-control">
<option value="0" ><%=setting[ID]%></option>
</select>
</td>
</tr>
</table>
Well it depends on how you retrieve data... do you use AJAX calls? Or do you need them when page is loaded?
Let's see the 2 scenarios
Note: in boths scenarios we assume you are returning a list of object like this:
public class Option{
private String value;
private String text;
//getter and setter
}
AJAX CALL: for this I assume we are using JQuery; in this case you will have in your JS or JSP file something like this:
$.ajax({
url : 'customchannel',
dataType : 'json',
contentType : 'application/json; charset=UTF-8',
type : 'GET',
success : function(items) {
$.each(items, function (i, item) {
$('#selectReportChannel').append($('<option>', {
value: item.value,
text : item.text
}));
});
},
error : function(data) {
}
});
<select id="selectReportChannel" class="form-control">
</select>
Page loaded In this case in your controller who will render the HTML page you can do something like this:
#Controller
public class CustomChannelController {
private Setting setting;
private Diagram diagram;
private Channel channel;
#RequestMapping(value = "/customchannel", method = RequestMethod.GET)
public ModelAndView getId(Model uiModel) {
uiModel.add("options", this.setting);
return new ModelAndView("yourPage", uiModel) ;
}
Then in the HTML page you can use JSTL in this way:
<table>
<tr>
<td>
<label class="col-md-12 control-label"> <%=language['UI.reportSetting.channel']%> : </label>
</td>
<td>
<select id="selectReportChannel" class="form-control">
<c:forEach items="${options}" var="option">
<option value="${option.value}">${option.text}</option>
</c:forEach>
</select>
</td>
</tr>
</table>
Ok, I have found a solution. First a need to create a Spring MVC Controller then a Service and link then the Controller to the Backbone model file.

How to get value of SelectBox when using AppEngine in Java, JavaScript and HTML

I am trying to create a way of filtering data that is stored within the datastore. The method I am using for this is a mixture of HTML, Javascript and Java Servlets. A form is made that allows data that is input into the Web Application to be sent to the Java Servlet. The Servlet then does the required actions and sends the user back to the page with the updated data. My problem is I have to use a SelectBox within this form that allows the user to select the atribute they wish to filter by, e.g. title, author. When the submit button is pressed, the value of the SelectBox is not sent as a parameter. This means a ERROR 500 appears as there isn't enough parameters to perform the function. I need to:-
Get the value of the SelectBox.
Pass it to the function with the parameter value in a text field. (Almost Completed)
Set the value of idvBook to equal the List that is sent back to the Webb Application.
Firstly, this is how I am creating the form with the SelectBox, TextInput and ButonInput:-
<div class="headline">Filter the DataStore</div>
<div class="info">To view individual records, select the attribute
you'd like to filter by and enter the value you'd like to find. Click
the button to generate the table based on your search criteria.</div>
<script type="text/javascript">
function filter(){
document.filterBooks.action="/get";
var idvBook = document.filterBooks.submit();
}
</script>
<form name="filterBooks">
<table>
<tr>
<td valign="top"><label for="attribute">Attribute</label></td>
<td>
<select id="attributeSelect">
<option value="void">Select Attribute</option>
<option value="id">ID</option>
<option value="title">Title</option>
<option value="author">Author</option>
<option value="publisher">Publisher</option>
</select>
</td>
</tr>
<tr>
<td valign="top"><label for="value">Value</label></td>
<td><input type="text" name="value" id="value"></input></td>
</tr>
<tr>
<td colspan="2" align="right"><input type="submit" value="Filter" onclick="filter()"></td>
</tr>
</table>
</form>
<table>
<tr>
<th>Book ID</th>
<th>Title</th>
<th>Description</th>
<th>Author</th>
<th>Publisher</th>
<th>Publish Date</th>
<th>Remove Book</th>
</tr>
<%
for (Book book : idvBook) {
%>
<tr>
<td><%=book.getId()%></td>
<td><%=book.getTitle()%></td>
<td><%=book.getDescription()%></td>
<td><%=book.getAuthor()%></td>
<td><%=book.getPublisher()%></td>
<td><%=book.getPublishDate()%></td>
<td><a class="done" href="/done?id=<%=book.getId()%>">Remove</a></td>
</tr>
<%
}
%>
</table>
</div>
Once this has been made, it is then placed in the HTML table located below the form (shown in the code above).
This sends the parameters to this servlet:-
public class ServletGetBooks extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse resp) throws IOException
{
resp.setContentType("text/plain");
resp.getWriter().println("Hello, world");
String attribute = request.getParameter("attributeSelect").toString();
String param = request.getParameter("value");
Dao.INSTANCE.getBooks(attribute, param);
resp.sendRedirect("/TodoApplication.jsp");
}
}
You can see another function is ran here. This function looks like this:-
public List<Book> getBooks(String attribute, String param) {
EntityManager em = EMFService.get().createEntityManager();
Query q = null;
if(attribute.equals("id"))
{
q = em.createQuery("select b from Book b where b.id = :id");
q.setParameter("id", param);
}
else if(attribute.equals("title"))
{
q = em.createQuery("select b from Book b where b.title = :title");
q.setParameter("title", param);
}
else if(attribute.equals("author"))
{
q = em.createQuery("select b from Book b where b.author = :author");
q.setParameter("author", param);
}
else if(attribute.equals("publisher"))
{
q = em.createQuery("select b from Book b where b.publisher = :publisher");
q.setParameter("publisher", param);
}
List<Book> books = q.getResultList();
return books;
}
How can i get it so that i can get the value of the SelectBox, run the function and set the result of this to equal idvBook?
EDIT-------------------------------------------------------------------------------------------------
I'll simplify things. I need this within <% ... %> tags:-
List<Book> idvBook = new ArrayList<Book>();
idvBook = dao.getBook("Value in SelectBox","Value in TextInput");
Your select box does not have a name attribute and its value is thus not sent with the form data.

How to display TABLE dynamically in JSP using SPRING MVC

I want to create a table dynamically in such a way that no of headers and data i can pass from JAVA class and on no. basis, jsp should create a table accordingly.
I have controller class in which i am returning model object which is my bean class. In that i have a list attribute in which i have hardcoded some values.These values should be by header names in the JSP table.
When i am rendering this model object to jsp then i am not able to retrieve the headers info. Plz suggest.
My contrller class loooks like this:
#RequestMapping
public ModelAndView getHeaders(PortletRequest portlestRequest, PortletResponse portletResponse){
ModelAndView mv = new ModelAndView();
TableDAO dao = new TableDAO();
List<String> headersList = dao.getHeaders();
TableView tableView = new TableView();
tableView.setTableHeaders(headersList);
mv.addObject("tableView",tableView);
mv.setView("tableView");
return mv;
}
My jsp:
<table>
<c:forEach var = "listValue" items = "${tableView.tableHeaders}">
<tr>
<%for(int i = 0;i<5;i++){ %>
<td>
<%=${listValue.get(i)} %>
</td>
<%} %>
</tr>
</c:forEach>
</table>
Someone plz help me on this.
Why are you looking over the list of headers twice? You dont need that scriptlet code.
Since tableView.tableHeaders returns a list of strings, you just need :
<table>
<tr>
<c:forEach var = "listValue" items = "${tableView.tableHeaders}">
<td>
<c:out value="${listValue}"/>
</td>
</c:forEach>
</tr>
</table>

submit onchange using request mapping in spring mvc

Generating a Jasper report depending on the user selected values from drop down (have two drop downs).
JSP:
<form:form name="f" action="${flowExecutionUrl}" modelAttribute="simpleReportSelector">
<table class="search">
<tr><th colspan="3"><fmt:message key="report.someextract"/></th></tr>
<tr>
<td><b><fmt:message key="somereport.sortdate"/></b>
<select id="firstfield" name="localDate" onchange="this.form.reloadPage.value='true';submit()">
<c:forEach var="dl" items="${dateList}">
<c:if test="${dl.selected==false}">
<option value="${dl.itemValue}">${dl.itemLabel}</option>
</c:if>
<c:if test="${dl.selected==true}">
<option selected="selected" value="${dl.itemValue}">${dl.itemLabel}</option>
</c:if>
</c:forEach>
</select>
</td>
<td><input type="hidden" id="reloadPage" name="reloadPage" value=""/></td>
<td><b><fmt:message key="somereport.equipNumber"/></b>
<select id="uld" name="uldNumber">
<c:forEach var="u" items="${uldList}">
<option value="${u.itemValue}">${u.itemLabel}</option>
</c:forEach>
</select>
</td>
</tr>
<tr><td class="right" colspan="3"><button type="submit" name="_eventId_exportReport">Submit</button></td></tr>
<tr class="hide">
<td><input id="submithidden" type="submit" value="submithidden" name="_eventId_submitButton" /></td>
</tr>
</table>
</form:form>
When user selects this particular menu from header, page populates with datelist and uldlist. datelist will be defaulted to today date and uldlist with 'select'. When user selects a previous date or future date, uldlist supposed to populate with different list.
controller:
#Controller
#RequestMapping("/uldReport.do")
public class ULDReport {
#Transactional(readOnly=true)
#RequestMapping(value="/uldReport.do",method = RequestMethod.GET)
public String setupForm(Model model, HttpServletRequest request, HttpServletResponse response) {
//code to populate datelist and uld list(populates using present day)
}
#Transactional(readOnly=true)
#RequestMapping(params={"reloadPage='true'"}, value="/uldReport.do", method = RequestMethod.GET)
public String setUpUld(Model model, HttpServletRequest request, HttpServletResponse response) {
//this should populate the uld list by using the date seelcted by user
}
#Transactional(readOnly=true)
#RequestMapping(params={"reloadPage='false'"}, method = RequestMethod.POST)
public ModelAndView processSubmit(#ModelAttribute SimpleReportSelector simpleReportSelector, Model model, HttpServletRequest request, HttpServletResponse response) throws IOException{
//some code
}
}
First method works good, but when I change the date, app directs to an error page. I think may be something with #RequestMapping, if I remove params from second and third method in controller, app submits with processandsubmit. What am I doing wrong?
This could be happening because of the way the URL is constructed. The fact that the page is loading a blank page means that it can't find anything that matches the criteria you have set up, and so it's silently failing.
For it to work as you expect, chances are you need to have the url formatted something like this:
/uldReport.do?reloadPage=true
or
/uldReport.do/reloadPage/true
depending on your setup.
But the point is that it needs to be in the URL and not a submitted field in your form, which it seems like it is right now.

Calling a jsp/html page using ajax in play 2.0

Can anyone guide me how can i call a jsp/html page using ajax in play framework?
I want to open a lightbox on click of a button and want to load that with a page containing data from database.
Currently i have just displayed the message using ajax. Below is the method inApplication.java
public static Result index()
{
return ok(index.render("Your new application is ready."));
}
My index.scala.html is:
#(products: List[Products])
#import helper._
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<h1>#products.size() product(s)</h1>
<table border=1>
<tr>
<td>Product Name</td>
<td>Quantity</td>
<td>Price</td>
</tr>
#for(product <- products) {
<tr>
<td>
#product.productname
</td>
<td>
#product.quantity
</td>
<td>
#product.price
</td>
<td id="items">
<input type="button" value="Add Product" name="#routes.Application.user(product.product_id)" id="but"/>
</td>
</tr>
}
</table>
<div class="result1" style="border: 1px solid black; padding: 5px;">not sent yet...</div>
<script type="text/javascript">
jQuery("#items a").click(
function () {
$.get(jQuery(this).attr("href"), function (data) {
$('.result').html(data);
});
return false;
}
)
</script>
You are on the good way.
Create a new action which will return only the html you need in your div (and not the complete html page).
public static Result detail(Integer productId)
{
Product product = .... (productId);
return ok(productDetail.render(product));
}
// with the route of course
productDetail.scala.html
#(product: Product)
My product #product.product_id is beautiful !
....
You must also add a jquery plugin to display your lightbox (there are a thousand...)
Your JsCode will be something like that:
$("#items a").click(function () {
$("#result").load($(this).attr("href"), function() {
displayPopup(); // code this
});
});
(Or maybe a totally different code if the plugin natively handle ajax...)
In resume, there is a lot of work to do, and many ways to do it.
Just try !

Categories