How to retrieve the file from SlingHttpServletRequest? - ajax

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 :(

Related

How do I compare and verify user input field to stored data BEFORE to sending form in ColdFusion

I’m updating a site for my brother who teaches training courses. He has a registration form on the site that collects name, age, address, etc. That information is sent to him through cfmail with a copy sent to the registrant. The registrants then mails in a check via snail-mail to complete the registration. (My brother does NOT want to use an online payment method.)
Included in the form is the course name, location and fee. He asked if it was possible to implement some sort of “Promo Code” to offer discounts to select users. I’ve added PromoCode and PromoCode_Fee columns in SQL and am able to make it all work throughout the process.
My problem is on the user end. If the user mistypes the PromoCode in the form, the app will obviously not register the discount, send the registration emails out with the standard fee, and store the registration info in the DB. The only way for the user to fix the PromoCode would be to re-register, which would re-send the emails and add a new registration to the DB.
What I’d like to do is verify that the user entered a valid PromoCode in the input field PRIOR to submitting the form by comparing what they typed to the PromoCode stored in the DB. If the PromoCode doesn’t match, add “Promo Code is invalid” under the input field.
I do this as a hobby, am self-taught and am not sure if it’s even possible (or good idea.) I imagine it’s not possible to do with ColdFusion and would most likely need some sort of JS or jQuery - both of which I’m pretty illiterate in.
I’ve been searching for hours to see if anyone had any similar questions, but have come up short. Any help or pointing me in the right direction would be greatly appreciated.
Here's the code I'm putting together:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="/scripts/jquery.validate.js"></script>
<script>
$(document).ready(function() {
var validator = $("#signupform").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2,
remote: "/components/promocodecomponent.cfc?method=validateUserName"
}
}
});
});
</script>
<div class="row justify-content-center">
<div class="col-10">
<form id="signupform" autocomplete="off" method="get" action="">
<table>
<tr>
<td class="label">
<label id="lfirstname" for="firstname">First Name</label>
</td>
<td class="field">
<input id="firstname" name="firstname" type="text" value="" maxlength="100">
</td>
<td class="status"></td>
</tr>
<tr>
<td class="label">
<label id="llastname" for="lastname">Last Name</label>
</td>
<td class="field">
<input id="lastname" name="lastname" type="text" value="" maxlength="100">
</td>
<td class="status"></td>
</tr>
<tr>
<td class="label">
<label id="lusername" for="username">Username</label>
</td>
<td class="field">
<input id="username" name="username" type="text" value="" maxlength="50">
</td>
<td class="status"></td>
</tr>
<tr>
<td class="field" colspan="2">
<input id="signupsubmit" name="signup" type="submit" value="Signup">
</td>
</tr>
</table>
</form>
</div>
</div>
Here's the component code:
component {
remote boolean function validateUserName(string username) returnFormat="json"{
if (arguments.username == "john") {
return true;
}
return "Username already in use";
}
}
Usually, you'd need to post some code that you've tried and isn't working. But you've outlined what you want and are just not sure where to start.
You can test just the value of the discount code before allowing the whole form to be submitted. You don't say how you're doing client-side form validation. I'd suggest using jQuery Validate to handle that, it's very easy to implement.
https://jqueryvalidation.org/documentation/
Go to the demo "The Remember The Milk sign-up form". This form checks the username field via Ajax before the rest of the form can be submitted.
var validator = $("#signupform").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2,
remote: "users.action"
}
}
});
If not using this framework, then just make an Ajax request when change is triggered on the discount code field and make sure there's a positive response from that before you allow the form to be submitted.
Also, you need to do server-side validation of the discount code when someone submits the form. If they've entered a discount code that is invalid, then don't allow the form to be processed until they enter a valid code or they clear the value from that field.
I do this as a hobby, am self-taught ... I imagine ... would most likely need some sort of JS or jQuery - both of which I’m pretty illiterate in.
The plugin is easy to use but there may be a slight learning curve depending on your jQuery and javascript skills. Bigger tasks are easier to tackle if you you break them into smaller ones and solve those one at a time. Start with the code snippet #AdrianJMoreno posted and delve into the documentation to understand what the code is doing and how:
validate() - a function that initializes the plugin for a specific form
rules - options that tells the plugin which form fields should be validated and how
remote - remote url to be called via ajax to validate a field's value. The remote endpoint should either return true/false or true/"some custom error message";
1. Build Sample Form
Once you have a sense of how the plugin works, move on to building a scaled down version of the Milk demo form using the code snippet.
JQuery and Validate libraries
<!-- modify js paths as needed -->
<script src="scripts/jquery-3.1.1.js"></script>
<script src="scripts/jquery.validate.min.js"></script>
Javascript initialization (so plugin validates the form)
<script>
$(document).ready(function() {
var validator = $("#signupform").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2,
remote: "users.action"
}
}
});
});
</script>
HTML form (only the fields in code snippet)
<form id="signupform" autocomplete="off" method="get" action="">
<table>
<tr>
<td class="label">
<label id="lfirstname" for="firstname">First Name</label>
</td>
<td class="field">
<input id="firstname" name="firstname" type="text" value="" maxlength="100">
</td>
<td class="status"></td>
</tr>
<tr>
<td class="label">
<label id="llastname" for="lastname">Last Name</label>
</td>
<td class="field">
<input id="lastname" name="lastname" type="text" value="" maxlength="100">
</td>
<td class="status"></td>
</tr>
<tr>
<td class="label">
<label id="lusername" for="username">Username</label>
</td>
<td class="field">
<input id="username" name="username" type="text" value="" maxlength="50">
</td>
<td class="status"></td>
</tr>
<tr>
<td class="label">
<label id="lsignupsubmit" for="signupsubmit">Signup</label>
</td>
<td class="field" colspan="2">
<input id="signupsubmit" name="signup" type="submit" value="Signup">
</td>
</tr>
</table>
</form>
2. Test (Sample Form)
Test out the form in a browser. Since all fields are required, leaving the fields blank and submitting should trigger error messages on submit
3. Create Remote URL
The live demo form uses a mocking library to simulate a remote ajax call. The mock url "users.action" must be replaced with a real url on your server. That url will point to a new component (or "CFC") you create. The component should contain a remote accessible method that validates a given username.
Keep things simple for the initial test. Have the method return true if the input equals a test value like "John" and false for everything else. Ultimately you'll replace that with real business logic, like a database lookup, but one step at a time.
YourComponentName.cfc
component {
remote boolean function validateUserName(string username) returnFormat="json"{
if (arguments.username == "john") {
return true;
}
return false;
}
}
4. Test (Remote URL)
To test a remote method in a browser, specify the path, name of the method to invoke, and any parameters that method expects. Verify the component returns the expected results. The result should be true for username=John and false for any other value.
Example url:
https://localhost/path/YourComponentName.cfc?method=validateUsername&username=john
Valid: UserName=John:
InValid: UserName=Bob:
5. Fix Remote URL
With the component working, update the javascript code to point to the new cfc. Omit the username parameter because the plugin will pass it to the ajax call automatically.
For example, if the component location on disk is:
c:\path\webroot\path\YourComponentName.cfc
Use the url:
/path/YourComponentName.cfc
JS Snippet:
...,
username: {
...,
remote: "/path/YourComponentName.cfc?method=validateUserName"
}
6. Test Form (.. are you sensing a theme?)
Test the final form again with both a valid and invalid usernames to confirm it works as expected.
Invalid usernames "Mike" or "Bob" should trigger an error
Valid username "John" should not trigger an error
Next Steps ...
Continue to expand the working example and learn more about the plugin features by adding some customization. The next steps are left as an exercise for the reader ...
Replace hard coded test logic in the cfc with a database lookup
Replace default error message "Please fix this field" with a more user friendly message
Change the appearance of valid and invalid fields using CSS

Datatable Editor 1.4 on JQUERY: async AJAX call. How I can to place after?

On index.html I have two pages JQM v.1.4.
In page-1 I´ve a form that get (nombreUsuario) and password and assign into respective vars.
In page-2 , I want to use the previous (nombreUsuario) for to get table that match with this nombeUsuario via AJAX on Datatable Editor 1.4.
My problem is that in page-1 the AJAX call is executed before that I enter nombreUsuario , therefore when pass to page-2 the table is empty , due the AJAX call was executed with variable empty , without nombreUsuario entry.
I´ve tried different code to get that AJAX call executed after entry nombreUsuario but I don’t get desired result . I´ve used async to false, but to do nothing .
Also, DataTable Editor AJAX document said :
Success: Must not be overridden as it is used internally in DataTables . Even so, I´ve used this option (taking jquery examples) and is true that don’t work (is yes, please tell me!) .
Now, will be more easy resolve it on JQM?. How can I to get nombreUsuario on page-1 and after pass to page-2 , then will execute AJAX call with this variable?
Any idea?. Thank you in advance!
index.html
<div data-role="page" id="page0">
<form id="formulario" >
<label> Usuario </label>
<input type="text" id="nombredeusuario" name="nombredeusuario">
<label> Password </label>
<input type="password" id="clave" name="clave" >
<input type="submit" value="Login" id="botonLogin">
</form>
...
<div data-role="page" id="page1">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Establecimiento</th>
<th>Telefono</th>
<th>E-mail</th>
<th>Nº de Plazas</th>
<th>Precio medio</th>
<th>E-mail (responsable)</th>
<th>Prueba (1) / Contrato (2)</th>
</tr>
</thead>
....
JS:
(form)
$('#formulario').submit(function() {
// recolecta los valores que inserta el usuario
var datosUsuario = $("#nombredeusuario").val()
var datosPassword = $("#clave").val()
...
JS (datatable editor 1.4)
$('#example').DataTable( {
//check. start
initComplete: function(settings, json) {
alert( 'DataTables has finished its initialisation.' );
},
//check.end
dom: "Tfrtip",
ajax: {
async: false, // don't work
url:"http://tripntry.com/_country/spain/b.cartasconmenu.front.back.demo/alacarte/php/clientes.php",
type: "POST",
data: function ( d ) {
d.site = $("#nombredeusuario").val(); // dont work!
//d.site = datosUsuario; //// dont work!
//d.site = "34280001"; // works (of course)
},
....
PHP (server side)
include( "../../php/DataTables.php" );
// Alias Editor classes so they are easy to use
use
DataTables\Editor,
DataTables\Editor\Field,
DataTables\Editor\Format,
DataTables\Editor\Join,
DataTables\Editor\Validate;
$site=$_POST['site'];
// Build our Editor instance and process the data coming from _POST
Editor::inst( $db, 'clientes' )
->fields(
Field::inst( 'tipo' )->validator( 'Validate::numeric' ), //this field another use
Field::inst( 'site' )->validator( 'Validate::notEmpty' )
)
->where( 'site', $site)
->process( $_POST )
->json();

WebMatrix AJAX INSERT not working

i'm trying to add an entry into my database and update a table i have created using AJAX. I think i'm halfway there, i can send my form contents to the "partial" page, but thats where it gets stuck?
Here's my content page:
#{
Layout = "~/_SiteLayout.cshtml";
WebSecurity.RequireAuthenticatedUser();
var db = Database.Open("StayInFlorida");
var rPropertyId = Request.QueryString["PropertyID"];
var Roominfo = "SELECT * FROM RoomInfo WHERE PropertyID=#0";
var qRoominfo = db.Query(Roominfo, rPropertyId);
}
<h2>Current Rooms</h2>
<table id="room-table" class="table table-bordered">
<tr>
<th>Room Name</th>
<th>Room Type</th>
<th>Room Description</th>
</tr>
#foreach(var row in qRoominfo){
<tr>
<td>#row.RoomName</td>
<td>#row.RoomType</td>
<td>#row.RoomDescription</td>
</tr>
}
</table>
<form id="add-room-form" action="#Href("~/Partials/AddRoom")">
<div class="row">
<span class="label"><label for="title">Room Name:</label></span>
<input type="text" name="roomname" id="roomname" size="50" />
</div>
<div class="row">
<span class="label"><label for="title">Room Type:</label></span>
<input type="text" name="roomtype" id="roomtype" size="50" />
</div>
<div class="row">
<span class="label"><label for="title">Room Description:</label></span>
<input type="text" name="roomdescription" id="roomdescription" size="50" />
</div>
<input type="hidden" name="propertyid" value="#rPropertyId" />
<button class="btn btn-success" id="submitbutton">Submit</button>
</form>
<script type="text/javascript">
$(function(){
$('#submitbutton').click(function(){
$.ajax({
type: "POST",
url: "/Partials/AddRoom",
data: $("#add-room-form").serialize(),
dataType: "text/plain",
success: function (data) {
$('#room-table').html(data);
}
return false;
});
});
});
</script>
and here is the partial page which "should" insert the data into the database:
#{
var db = Database.Open("StayInFlorida");
var sql = "INSERT INTO RoomInfo (PropertyID, RoomName, RoomType, RoomDescription, LastModified) " +
"VALUES (#0, #1, #2, #3, GetDate())";
var propertyid = Request["propertyid"];
var roomname = Request["roomname"];
var roomtype = Request["roomtype"];
var roomdescription = Request["roomdescription"];
db.Execute(sql, propertyid, roomname, roomtype, roomdescription);
}
In theory, it should write the info to the database, and then refresh my table, so im guessing something isn't quite right with the javascript?
You cannot sent the data through an ajax call is because you cannot even start the request. You are using the function to trigger when a click is made. But there will be no click event.
Reason: There is no button with the ID for click event. See Click trigger issue section below.
Tip: To check whether there is any Request to the server or not, you should make use of this. In every browser when you press F12 you get Developer Tools opened. Make sure you are on network tab. You will be able to check any network request made to server through there. Ajax requests are also saved there as a log, there status and everything is present there. That will be a basic but a powerfull tool to help you out in understanding how Ajax requests are made.
There are certain issues in your code too.
Issue in the HTML: There is an error in your code, look at the submit button. Its having code as:
<button class="btn btn-success" type="submit" value="Submit"/>Submit</button>
Which should be:
<button class="btn btn-success" type="submit" value="Submit">Submit</button>
And then, I should change that too the following because the type="submit" will submit the form instead of creating an ajax request. I used your page in my website and just replaced the DataBase objects and replaced them with simple Response like Response.Write() and wrote the variables that I caught:
<button class="btn btn-success" id="submitbutton">Submit</button>
So the code that I changed the above one to is like this:
#{
if(IsPost){
var propertyid = "1";
var roomname = Request["roomname"];
var roomtype = Request["roomtype"];
var roomdescription = Request["roomdescription"];
var lastmodified = DateTime.Now;
// here you will write the data to database using Database.Execute
// Remember you should write the ajax response
// here as a result of Response.Write()
// However if you still want to load that page, its OK!
}
}
As mentioned earlier, you were write the propertyid as "'1'" I changed that to "1". But in case you want to execute as "'1'" its ok too.
Click trigger issue:
There were some other issues too. You were using:
$('#submitbutton').click(function(){
But there was no button with the ID submitbutton. So I changed the id of the button you were using there.
What I changed in your code:
What change I made in your code was I changed the POST request to GET. To have a look at what variables are being sent to server and what results I get. I had it easier to make use of this code as GET request was easily able to check then POST request.
If you still want to use POST request you should try to serialize() the form as JSON and send it to server. But GET will be easy.
Then I gave another field to the $.ajax section as:
data: 'roomname=' + $('#roomname').val() +
'roomtype=' + $('#roomtype').val() +
'roomdescription=' + $('#roomdescription').val(),
This will create a string of the data to be sent. And then it will be caught on that page. And I removed if(IsPost) too. I was able to get the result of the Response. So what you can do is to change the Response of the request and write is as:
$("#room-table").html(response);
And the table will be changed! This will remove the previous data in the table Or even whole of the table and update it with the data recieved from the Response. And then I was able to send the request to server, process the QueryString and then write a response and then using $('#idofelement').html(response) I wrote it in the specific area. You can try it as I did.
The full code that I used was:
One the main page I had this code:
#{
Layout = "~/_SiteLayout.cshtml";
}
<h2>Current Rooms</h2>
<div class="row">
<span class="label"><label for="title">Room Name:</label></span>
<input type="text" name="roomname" id="roomname" size="50" />
</div>
<div class="row">
<span class="label"><label for="title">Room Type:</label></span>
<input type="text" name="roomtype" id="roomtype" size="50" />
</div>
<div class="row">
<span class="label"><label for="title">Room Description:</label></span>
<input type="text" name="roomdescription" id="roomdescription" size="50" />
</div>
<button class="btn btn-success" id="submitbutton" value="Submit" >Submit</button>
<script type="text/javascript">
$(function(){
$('#submitbutton').click(function(){
$.ajax({
url: '/Partials',
data: 'roomname=' + $('#roomname').val() + 'roomtype=' +
$('#roomtype').val() + "roomdescription=" +
$('#roomdescription').val(),
dataType: 'text',
contentType: 'text/html',
success: function(response) {
$("#body").html(response);
},
error: function(data){
alert('Something went wrong');
}
});
});
});
</script>
I changed the page to partials only and used it. Here is the content for that page.
#{
var propertyid = "1";
var roomname = Request["roomname"];
var roomtype = Request["roomtype"];
var roomdescription = Request["roomdescription"];
var lastmodified = DateTime.Now;
Response.Write("Room name: " + roomname + "<br>Room Type: "
+ roomtype + "<br>Room Description: " + roomdescription +
"<br>Property: " + propertyid);
}
Now its upto you to use the Database variables here. Where I used Response.Write and other codes You can use the Database methods. And also you can add WebSecurity method.
The Database.Execute method requires the SQL to be executed to be passed in first. You don't appear to be passing it in at all. Also, I assume that PropertyId is an integer? If so, you should not surround it in quotes. In fact, you should try delimiting values that will be passed in via parameter at all. That's one of the benefits of using parameters. Try this:
#{
if(IsPost){
var db = Database.Open("StayInFlorida");
var sql = "INSERT INTO RoomInfo (PropertyID, RoomName, RoomType, RoomDescription, LastModified) " +
"VALUES (#0, #1, #2, #3, GetDate())";
var propertyid = 1;
var roomname = Request["roomname"];
var roomtype = Request["roomtype"];
var roomdescription = Request["roomdescription"];
db.Execute(sql, propertyid, roomname, roomtype, roomdescription);
}
}
You are hardcoding the Properytid at the moment. If you want that to be dynamic, add a hidden field to your AJAX form and set the value to rPropertyId:
<input type="hidden" name="propertyId" value="#rPropertyId" />
Then you can alter the 4th line in the snippet above:
var propertyId = Request["propertyId"];

Drop down dependencies with Servlet and 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

How to retrieve multiple records from Jquery to my RazorView page

I have a button "btnGetAddress" on my razor page .On clik of this button,I am calling a Jquery to get my addressItmes object to be displayed on to my View page.
On clicking "btnGetAddress" I am able to hit my "JsonResult GetAddresses()" and retrieve records within my Jquery (success: function (data)).and this data has multiple address records. But I do not know how to take this data to my view .Please help me to get my data to be displayed on to my View
When my page get loaded,the user will see only the "btnGetAddress" button .When the user click on the btnGetAddress, it will call the Jquery Click function to fetch all address records from database and display each set of records on the page
$("#btnGetAddress").click(function () {
debugger;
var selected = $("#ddlType").val();
if (selected == "")
{ selected = 0; }
var dataToSend = {
SelectedTypeId: selected
};
$.ajax({
type: "GET",
url: '#Url.Action("GetAddresses", "Content")',
data: { SelectedTypeId: selected },
success: function (data) {
debugger;
},
error: function (error) {
var verr = error;
alert(verr);
}
});
pasted below is my JsonResult GetAddresses() which gets called to retrieve addressItems
public JsonResult GetAddresses()
{
model.AddressItems = AddressService.RetrieveAllAddress();
// My AddressItems is of type IEnumerable<AddressItems>
return Json(model.AddressItems, JsonRequestBehavior.AllowGet);
}
Here is my razor View Page where the address records are to be displayed.
........................
<input type="submit" id="btnGetAddress" name="btnSubmit" value="Show Addresses" />
if (!UtilityHelper.IsNullOrEmpty(Model.AddressItems))
{
foreach (var AddressRecord in Model.AddressItems)
{
<fieldset >
<legend style="padding-top: 10px; font-size: small;">Address Queue(#Model.NumRecords)
</legend>
<table>
<tr>
<td>
<span>Index</span>
</td>
<td>
</td>
<td>
<input type="submit" id="btnDelete" name="btnSubmit" value="X" />
<br />
</td>
</tr>
<tr>
<td>
<span>Address1</span>
<br />
</td>
<td>
#Html.EditorFor(model => AddressRecord.Address )
#Html.ValidationMessageFor(model => AddressRecord.Address)
</td>
</tr>
<tr>
<td>
<span>Description</span>
<br />
</td>
<td>
#Html.EditorFor(model => AddressRecord.Description)
#Html.ValidationMessageFor(model => AddressRecord.Description)
</td>
</tr>
<tr>
<td>
<input type="submit" id="btnSave" name="btnSubmit" value="Save" />
</td>
<td>
<input type="submit" id="btnDelete" name="btnSubmit" value="Delete" />
</td>
</tr>
</table>
</fieldset>
}
}
<fieldset>
Or is there any better way to achieve my objective?
Since you are getting the data via ajax you should use a jquery template engine. Basically get the data the way you are and on success you do something like
<script language="javascript" type="text/javascript">
$(function () {
$.getJSON("/getprojects", "", function (data) {
$("#projectsTemplate").tmpl(data).appendTo("#projectsList");
});
});
</script>
<script id="projectsTemplate" type="text/html">
<section>
<header><h2>Projects</h2></header>
<table id="projects">
<th>Name</th>
{{tmpl(items) "#projectRowTemplate"}}
</table>
</section>
</script>
<script id="projectRowTemplate" type="x-jquery-tmpl">
<tr>
<td>${name}</td>
</tr>
</script>
<div id="projectsList"></div>
Now each template engine is different but the above gives you an idea of what you can do
If you want to return JSON object in your controller, you are going have to turn your view into a string and return it as part of the message. If you google there are some methods out there that can do this.
However, I really think that's the hard way, why not take the data you get from the JSON in the controller and put it in a MODEL and then return your VIEW with the model data passed in. I think that's the easier way.

Resources