Drop down dependencies with Servlet and AJAX - ajax

I have a 3 drop down list. The 1st drop down is the parent and I want to populate the the 2nd drop down when user select a value from 1st, then populate the 3rd drop down based on 2nd. I'm using servlet to declare the values. Here's the code:
Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
TblBIRFormNoDAO birdao = DAOFactory.getDaoManager(TblBIRFormNo.class);
List<TblBIRFormNo> birtypelist = birdao.getAllBirFormNumber();
request.setAttribute("birtypelist", birtypelist);
String bir = request.getParameter("bfnsCode");
TblTaxTypeDAO taxdao = DAOFactory.getDaoManager(TblTaxType.class);
if(bir != null){
List<TblTaxType> taxtypelist = taxdao.findAlltaxtCode(bir);
String json = null;
json = new Gson().toJson(taxtypelist);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
String tax = request.getParameter("taxtCode");
TblTaxTypeDAO tdao = DAOFactory.getDaoManager(TblTaxType.class);
if(tax != null){
List<TblTaxType> taxdesclist = tdao.findAlltaxtDesc (tax);
String json = null;
json = new Gson().toJson(taxdesclist);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
request.getRequestDispatcher("/servlet-test.jsp").forward(request, response);
}
From this servlet. I'm getting the value of 1st drop down but it seems I can't get the value of the selected value that will use to populate the 2nd and 3rd.
jsp + AJAX:
<script type="text/javascript">
$(document).ready(function() {
$('#bfnsCode').change(function() {
$.get('Test', function(responseJson) {
var $select = $('#bfnsCode');
$select.find('option').remove();
$.each(responseJson, function(key, value) {
$('<option>').val(key).text(value).appendTo($select);
});
});
});
});
</script>
<label style="font-size: 17px;">BIR-Form Number</label><br>
<select name="bfnsCode" id="bfnsCode" class="sel" style="width: 245px; margin-left: 0;">
<option selected="selected" value=""></option>
<c:forEach var="bircode" items="${birtypelist}">
<option value="${bircode.bfnsCode}">${bircode.bfnsCode}</option>
</c:forEach>
</select>
<br><br>
<label style="font-size: 17px;">Tax Type</label><br>
<select name="taxtCode" id="taxtCode" class="sel" style="width: 245px; margin-left: 0;">
<option selected="selected" value=""></option>
<c:forEach var="taxtype" items="${taxtypelist}">
<option value=""></option>
</c:forEach>
</select>
<br><br>
<label style="font-size: 17px;">Account Code</label><br>
<select name="taxtDesc" id="taxtDesc" class="sel" style="width: 245px; margin-left: 0;">
<option selected="selected" value=""></option>
<c:forEach var="taxdesc" items="${taxdesclist}">
<option value="${taxdesc.taxtDesc}">${taxdesc.taxtDesc}</option>
</c:forEach>
</select>
This part, the only value that is showing is the 1st drop down. What are the missing codes for AJAX? or the servlet?

please find this reference it would be much helpful Reference
Scenario's that i could suggests you is ,,
1.Onload of the page you may get the first drop down to be loaded
2.Onchange of first write the ajax calls to pass the first drop down value as input in ajax calls and append the second select options
3.On change of second write the ajax calls to pass the second drop down value as input to the servlet in ajax calls and append the third select options

When the value of first drop down changes you have to pass the selected value to jquery get function such as this,
<script type="text/javascript">
$(document).ready(function() {
$('#bfnsCode').change(function() {
var $bfnscode=$("select#bfnsCode").val();
$.get('Test',{bfnsCode:$bfnscode},function(responseJson) {
var $select = $('#taxtCode');
$select.find('option').remove();
$.each(responseJson, function(key, value) {
$('<option>').val(key).text(value).appendTo($select);
});
});
});
});
You never passed parameter to your get function neither did you populate your second drop down with your response. You have tried to populate the same select option with no values from servlet. The above code should work for you. Good luck!
Update: I just noticed that you have tried to forward the request to jsp. You should not redirect your page when making AJAX calls since you are simply updating the drop down list and the jquery takes care of getting the response from servlet and updating the interface. Remove this from your servlet code,
request.getRequestDispatcher("/servlet-test.jsp").forward(request, response);//remove this line

Related

Pass a List to Javascript function in Thymeleaf

I have seen several examples of sending individual parameters to a JavaScript function, but not a List.
When I try to pass a list, it comes to function as a big string. This is what I have:
<select id="namespace" name="namespace"
th:responseList="${responseList}"
th:onchange="javascript:print(this.getAttribute('responseList'));">
<option value="">Select Source Namespace</option>
<option th:each="item : ${responseList}"
th:value="${item.namespace}"
th:text="${item.namespace}"></option>
</select>
function print(responseList) {
console.log(responseList);
}
Try this
<script th:inline="javascript">
var list = [[${responseList}]];
console.log(list );
</script>
Hope work for you

How to retrieve the file from SlingHttpServletRequest?

I am entirely new to development. So please forgive me if I ask anything wrong. I am trying to upload multiple files to the webserver. The webserver is running on Adobe Enterprise Manager. I have a JSP page that submits my form through an AJAX Call to a servlet as a SlingHttpServletRequest.
My Jsp page along with the AJAX CALL:
<div class="content">
<form method="POST" action="/servletpath" enctype="multipart/form-data" id="form-id">
<table>
<tr>
<td><label>...</label></td>
<td>
<select id="id1">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
</td>
</tr>
<tr>
<td><label>...</label></td>
<td>
<select id="id2">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
</td>
</tr>
<tr>
<td><label>Choose Files</label></td>
<td><input id="fileInput" type="file" name="uploadingFiles" onchange="updateSize();" multiple>
selected files: <span id="fileNum">0</span>;
total size: <span id="fileSize">0</span></td>
</tr>
<tr>
<td><input type="submit" value="Upload files" onclick="uploadFiles()"></td>
<td><input type="button" value="Start Comparison" onclick="location.href='/startComparison'"></td>
</tr>
</table>
</form>
<script type="text/javascript">
var uploadFiles = function () {
alert("inside uploadFiles");
var formData = new FormData();
formData = formData.append("file1",document.getElementById("fileInput").files[0].name);
alert("appended file..."+document.getElementById("fileInput").files[0].name);
var statusWin = CQ.Ext.Msg.wait("Processing request", "Uploading Files...");
CQ.Ext.Ajax.request({
url: CQ.HTTP.externalize("/servletpath"),
method: "POST",
processData:false,
contentType:false,
scope: this,
params: {
"file1":document.getElementById("fileInput").files[0],
"file2":document.getElementById("fileInput").files[1]
},
success:...,
failure: function (response) {
if (statusWin.isVisible()){
statusWin.hide();
}
alert("Response Body :: "+response);
alert("Response Status :: "+response.status);
}
});
}
</script>
</div>
Servlet Class:
#SlingServlet(paths="/servletPath", methods = "POST", metatype=true)
public class SampleServlet extends SlingAllMethodsServlet {
#Reference
private ResourceResolverFactory resolverFactory;
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
throws IOException,ServletException {
log.info("I am inside POST method of Sample Servlet");
log.info("SlingHTTPRequest content type is :: "+request.getContentType());
log.info("getParamter Attached file is :: "+request.getParameter("file1"));
}
boolean isMultipart = org.apache.commons.fileupload.servlet.ServletFileUpload.isMultipartContent(request);
log.info("Is this a Multipart Request :: "+isMultipart);
}
Log Output:
I am inside POST method of Sample Servlet
SlingHTTPRequest content type is :: :: application/x-www-form-urlencoded; charset=UTF-8 getParamter
Attached file is :: [object File]
Is this a Multipart Request :: false
I tried the below approaches but did not work
https://helpx.adobe.com/experience-manager/using/uploading-files-aem1.html -> This uses jquery ajax call to upload file, but chrome did not support it. So not able to pursue this.
Tried to get the files from the form using document.getElementById("fileInput").files[i] then appended it to FormData() object then sent it. But still don't know how to retrieve the file from the request Object.
ISSUES:
Even though I submit the request as Multipart, isMultipart check always returns false for me inside the doPOST method inside the servlet.
request.getParameter(String) returns a String and I am not sure How to retrieve the file object
request.getParameter("file2") returns [object File]. Not sure how to retrieve the file from this one
I am really stuck guys. Any help or any direction would be much appreciated.Since my entire code runs on AEM I am not able to debug with breakpoints. I am able to get log outputs only :(

Getting selected value in JSP to Servlet without page refresh

I want to get the value of the bfnsCode select tag onchange to servlet without page refreshing. And also the value of taxtCode. How should I do that? Here's my code...
JSP:
<label style="font-size: 17px;">BIR-Form Number</label><br>
<select name="bfnsCode" id="bfnsCode" class="sel" style="width: 245px; margin-left: 0;">
<option selected="selected" value=""></option>
<c:forEach var="bircode" items="${birtypelist}">
<option value="${bircode.bfnsCode}">${bircode.bfnsCode}</option>
</c:forEach>
</select>
<br><br>
<label style="font-size: 17px;">Tax Type</label><br>
<select name="taxtCode" id="taxtCode" class="sel" style="width: 245px; margin-left: 0;">
<option selected="selected" value=""></option>
<c:forEach var="taxcode" items="${taxtypelist}">
<option value="${taxcode.taxtCode}">${taxcode.taxtCode}</option>
</c:forEach>
</select>
<br><br>
<label style="font-size: 17px;">Account Code</label><br>
<select name="taxtDesc" id="taxtDesc" class="sel" style="width: 245px; margin-left: 0;">
<option selected="selected" value=""></option>
<c:forEach var="taxdesc" items="${taxdesclist}">
<option value="${taxdesc.taxtDesc}">${taxdesc.taxtDesc}</option>
</c:forEach>
</select>
servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
TblBIRFormNoDAO birdao = DAOFactory.getDaoManager(TblBIRFormNo.class);
List<TblBIRFormNo> birtypelist = birdao.getAllBirFormNumber();
request.setAttribute("birtypelist", birtypelist);
String bir = request.getParameter("bfnsCode");
TblTaxTypeDAO taxdao = DAOFactory.getDaoManager(TblTaxType.class);
if(bir != null){
Debugger.print("BFNSCODE : "+bir);
List<TblTaxType> taxtypelist = null;
taxtypelist = taxdao.findAlltaxtCode(bir);
request.setAttribute("taxtypelist", taxtypelist);
}
String tax = request.getParameter("taxtCode");
TblTaxTypeDAO tdao = DAOFactory.getDaoManager(TblTaxType.class);
if(tax != null){
Debugger.print("TAXCODE : "+tax);
List<TblTaxType> taxdesclist = tdao.findAlltaxtDesc(bir, tax);
request.setAttribute("taxdesclist", taxdesclist);
}
request.getRequestDispatcher("/servlet-test.jsp").forward(request, response);
}
From this code in servlet the request getParameter gives a null value. How to get the right value when user selected a value in drop down list?
P.S
2nd drop down is based on 1st and 3rd drop down is based on 2nd so the 2nd and 3rd drop down is empty as of the moment because I'm not getting the value of parameter bfnsCode(1st drop down). Please help me out, I badly need this.
if you're new to ajax i would use jquery, it's very easy to do ajax with it.
Ajax get petition . The documentation is very easy and understandable

Knockout.js: Null value in viewModel throws exception on foreach in view

So I have a viewModel that looks like this
self.zones = ko.observableArray(zones);
ko.utils.arrayForEach(self.zones(), function (zone) {
//Get all rooms for the zone
zone.rooms = getChildren("Organization", "Organization", zone.ID);
if (zone.rooms.length > 0) {
zone.buttons = ko.observableArray([]);
//For each Room in Zone find the Buttons and add them to the Zone.buttons ObservableArray
ko.utils.arrayForEach(zone.rooms, function (room) {
room.buttons = getChildren("Organization", "ButtonAssign", room.ID, { scheduleID: self.scheduleID });
ko.utils.arrayForEach(room.buttons, function (button) {
zone.buttons.push(button);
});
});
}
So a you can see a zone has a property called buttons that is an Observable array
In my view I loop through each zone and output the buttons but one of my zones does not contain any buttons and throws this exception:
Error: Unable to parse bindings.
Message: ReferenceError: buttons is not defined;
Bindings value: foreach:buttons
<table>
<tbody>
<tr data-bind="foreach: zones" style="vertical-align: top;">
<div class="zoneDiv">
<span data-bind="text: Name"></span>
<div data-bind="foreach:buttons" class="buttonsList">
<div class="buttonField">
<div data-bind="text: Name" style="float: left; width: 140px;">
</div>
</div>
<input type="hidden" data-bind="value: ID" />
</div>
</div>
</td>
</tr>
</tbody>
</table>
So my question is: How do you check for null values in an observable array before you start looping on it?
Additionally how do you check for a null value on a single property such as button.Name so that if the button has a name Ill write it out in a div and if it does not I wont write out anything (Or a default text).
So basically null checks on viewmodel properties in the view so I wont get this exceptions
Thanks
So my question is: How do you check for null values in an observable
array before you start looping on it?
Use the if binding: http://knockoutjs.com/documentation/if-binding.html
But in the case of your code, why don't you just set an empty observableArray, that way you don't need to introduce any conditionals:
self.zones = ko.observableArray(zones);
ko.utils.arrayForEach(self.zones(), function (zone) {
zone.rooms = getChildren("Organization", "Organization", zone.ID);
zone.buttons = ko.observableArray([]);
if (zone.rooms.length > 0) {
//For each Room in Zone find the Buttons and add them to the Zone.buttons ObservableArray
ko.utils.arrayForEach(zone.rooms, function (room) {
room.buttons = getChildren("Organization", "ButtonAssign", room.ID, { scheduleID: self.scheduleID });
ko.utils.arrayForEach(room.buttons, function (button) {
zone.buttons.push(button);
});
});
}
});

Sending form field values to params hash - rails

I have a partial that I call in layouts/application.html.erb to display a form for a search. The user chooses values from the two select fields; then, should hit enter to render a view with search results.
Here is the partial:
** _search.html.erb:
<form name="classic">
<select name="countries" size="1" onChange="updatecities(this.selectedIndex)" style="width: 150px">
<option selected>Select A Brand</option>
<option value="usa">Opel</option>
<option value="canada">Cheverolet</option>
<option value="uk">Scoda</option>
</select>
<select name="cities" size="1" style="width: 150px">
</select>
</form>
<script type="text/javascript">
var countrieslist=document.classic.countries
var citieslist=document.classic.cities
var cities=new Array()
cities[0]=""
cities[1]=["Vectra|vectravalue", "Corsa|corsavalue"]
cities[2]=["Optra|optravalue", "Lanos|lanosvalue"]
cities[3]=["Octavia|octaviavalue", "Fleshia|fleshiavalue"]
function updatecities(selectedcitygroup){
citieslist.options.length=0
if (selectedcitygroup>0){
for (i=0; i<cities[selectedcitygroup].length; i++)
citieslist.options[citieslist.options.length]=new Option(cities[selectedcitygroup][i].split("|")[0], cities[selectedcitygroup][i].split("|")[1])
}
}
</script>
The javascript is just to filter the second select dropdown based on the first select dropdown. What I need to do is to send the values chosen in this form in the URL for params hash so that I can act on it in the controller and display the search results. I could use link_to.
How do I include the selected values from the form fields in link_to?
Your help is appreciated. Thanks!
Serialize the form and send the data to the server. The selected value is passed as the hashvalue where the key is the "id" for the select tag.

Resources