I want to send a variable from jQuery to my Servlet. Here is my jQuery:
<script>
$('#myModal').on('show.bs.modal', function(e) {
var metrics_key = $('.createAlarm').val();
var metrics_label = $(".createAlarm option:selected").text();
// Now you have the key and label in variables.
// Write the key into the textfield.
$('#myModal input[name="name"]').val(metrics_key);
// Change the HTML of an element to the label.
$('#myModal label[for="priority"]').html(metrics_label);
var val = $('#priority').text();
console.log(val);
$.post('/sampleapp/createAlarm', { val : val},
function() { // on success
alert("Insertion successful! of "+val);
})
.fail(function() { //on failure
alert("Insertion failed." +val);
});
});
</script>
On the servlet, I am using:
String Metric = request.getParameter("val");
Please find below the HTML Code. When I select a value from dropdown and click on Create Alarm button, the bootstrap modal pops up. I want to pass all those values from the popup to my servlet. I am able to do all that except the value I am setting in jQuery.
<div class="container" style="padding-top: 60px;" >
<select class="createAlarm" id="createAlarm" name="metrics">
<option value="cpuUsage">CPU Usage</option>
<option value="memoryUsage">Memory Usage</option>
<option value="diskRead">Disk Read</option>
<option value="diskWrite">Disk Write</option>
<option value="diskUsage">Disk Usage</option>
<option value="netUsage">Net Usage</option>
</select>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" data-whatever="Create Alarm">Create Alarm</button>
</div>
<!-- Modal- Create Alarm -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Create Alarm</h4>
</div>
<form action="/CMPE283_Project2/createAlarm" method="post" id="addcard" class="form-horizontal" role="form">
<div class="modal-body" style="height: 170px;">
<div class="form-group" style="height: 30px;">
<label for="title" class="col-md-3 control-label">Name</label>
<div class="col-md-9">
<input type="text" class="form-control" name="alarmName">
</div>
</div>
<div class="form-group" style="height: 30px; margin-bottom:30px;">
<label for="title" class="col-md-3 control-label">Description</label>
<div class="col-md-9">
<textarea class="form-control" name="desc"></textarea>
</div>
</div>
<div class="form-group">
<label for="priority" id="priority" name="priority" class="col-md-3 control-label">
<input type="text" class="form-control" name="name">
</label>
<div class="col-md-9">
<div class="col-md-3">
<select name="sign" class="form-control">
<option value="lessthan"><</option>
<option value="greaterthan">></option>
<option value="lessthanequalto"><=</option>
<option value="greaterthanequalto">>=</option>
</select>
</div>
<div class="col-md-3">
<input type="text" class="form-control" name="threshold">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button class="btn btn-primary" id="formSubmit" type="submit">Create Alarm</button>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
But i m getting null value for the Metric. Please help. Thanks.
insead of post try to use this way
$.ajax({
url : url,
type : "post",
data : values,
success : function(data) {
if (data.errorCode == "SUCCESS") {
} else {
}
},
error : function() {
alert("failure");
}
where values is you form or JSON
otherway try {"val" : val}
Related
I am trying to save an image inserted by an <input> field in a form by the user to a folder named imgs under the WEB-INF folder and store in the table column of the product the path of that photo so i can later display them in a products page for my online shop.
I don't know how to send the image to the java file (using jdbc server) so i can save it and also how i can save it. I have researched online but I have not fount what i am looking for. Below is my .jsp file.
<body>
<%
if(request.getParameter("btn") != null){
String name = request.getParameter("name");
String description = request.getParameter("description");
double price = Double.valueOf( request.getParameter("price"));
String brand = request.getParameter("brand");
String type = request.getParameter("type");
int quantity = Integer.parseInt( request.getParameter("quantity"));
File picture =
Client client = Client.create();
WebResource webResource =client.resource("...link.../"+name+"/"+description+"/"+price+"/"+brand+"/"+type+"/"+quantity+"/"+picture);
ClientResponse myresponse = webResource.accept("text/plain").get(ClientResponse.class);
}
%>
<div class="p-5" >
<h1 id="title" class="d-flex justify-content-center" style="font-size:4rem;">Edit your Profile</h1>
<form class="container " method="post">
<div class="form-row">
<div class="form-group col-6">
<label for="name">Product name:</label>
<input class="form-control" type="text" name="name"><br>
</div >
</div>
<div class="form-row">
<div class="form-group col-6">
<label for="description">Description:</label>
<textarea class="form-control" name="description" cols="40" rows="5"></textarea><br>
</div >
</div>
<div class="form-row">
<div class="form-group col-3">
<label for="price">Price:</label>
<input class="form-control" type="number" name="price"><br>
</div >
<div class="form-group col-6">
<label for="brand">Product brand:</label>
<input class="form-control" type="text" name="brand"><br>
</div >
</div>
<div class="form-row">
<div class="form-group col-6">
<label for="type">Product type(running, walking, casual ,etc...):</label>
<input class="form-control" type="text" name="type"><br>
</div >
<div class="form-group col-6">
<label for="quantity">Available quantity:</label>
<input class="form-control" type="text" name="quantity"><br>
</div >
</div>
<div class="form-row">
<div class="form-group col-6">
<label for="picture">Product picture:</label>
<input class="form-control" type="file" name="picture"><br>
</div >
</div>
<button type="submit" name="btn">Sign in</button>
</form>
</div>
</body>
I am working with Java ArrayList and thymeleaf. I need to use the list in thymeleaf for adding value dynamically. I don't understand how to do that?
Model
public class MedicineDTO {
private Long brandId;
private Long stockId;
private double quantity;
private double discount;
private double total;
}
public class InvoiceDTO {
private String customerName;
private String mobileNumber;
private List<MedicineDTO> medicineDTOList;
private double averageDiscount;
private double totalDiscount;
private double grandTotal;
}
Controller
#RequestMapping(value = "/pos")
public String getPOS(Model model) {
List<Brand> brandList = brandService.getAllBrands();
List<MedicineDTO> medicineDTOList = new ArrayList<>();
InvoiceDTO invoiceDTO = new InvoiceDTO();
invoiceDTO.setMedicineDTOList(medicineDTOList);
model.addAttribute("medicinedto", new MedicineDTO());
model.addAttribute("invoicedto", invoiceDTO);
model.addAttribute("brands", brandList);
return "pos";
}
#PostMapping(value="/pos/payment")
public String makePayment(InvoiceDTO invoiceDTO){
System.out.println(invoiceDTO);
service.makePayment(invoiceDTO);
return "invoice/invoice";
}
pos.html
<form id="posForm" th:action="#{/pos/payment}" th:object="${invoicedto}" method="post">
<div class="card-body">
<div class="form-group row">
<label class="col-sm-2 col-form-label" for="name">Customer Name</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="name"
th:field="*{customerName}"
placeholder="Enter Customer Name">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label" for="mobile">Mobile No</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="mobile"
th:field="*{mobileNumber}"
placeholder="Enter Mobile Number">
</div>
</div>
<div class="col-sm-4 col-md-2">
<button type="button" class="btn btn-success btn-sm add-row">
Add
</button>
<button type="reset" class="btn btn-primary btn-sm">
Reset
</button>
</div>
<table class="table" id="brand_tbl">
<thead>
<tr>
<th>Brand Name</th>
<th>Expired Date</th>
<th>Stock</th>
<th>Quantity</th>
<th>Price</th>
<th>Discount %</th>
<th>Total</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr th:object="${medicinedto}">
<td>
<select id="selectBrand1" class="form-control select2"
th:field="*{brandId}"
onchange="changeBrand(this);"
style="width: 100%;">
<option value=""> --</option>
<option th:each="brand : ${brands}"
th:value="${brand.id}"
th:utext="${brand.name}">
</select>
</td>
<td style="width:15%">
<select id="selectDate1" class="form-control select2"
onchange="changeDate(this);"
style="width: 100%;">
<option value=""> --</option>
</select>
</td>
<td style="width:10%">
<input type="number" class="form-control" id="stock1"
placeholder="" disabled>
<input type="hidden" id="stockId1" th:field="*{stockId}">
</td>
<td style="width:10%">
<input type="number" class="form-control" id="quantity1"
th:field="*{quantity}"
onchange="changeQuantity(this);"
placeholder="">
</td>
<td style="width:12%">
<input type="number" class="form-control" id="price1"
placeholder="" disabled>
</td>
<td style="width:12%">
<input type="number" class="form-control" id="discount1"
onchange="changeDiscount(this);"
placeholder="0">
<input type="hidden" id="discountAmount1" th:field="*{discount}">
</td>
<td style="width:12%">
<input type="number" class="form-control" id="total1"
th:field="*{discount}"
placeholder="" readonly>
</td>
<td>
<button type="button"
class="btn btn-block btn-danger btn-sm delete-row">
Delete
</button>
</td>
<div th:text="${invoicedto.medicineDTOList.add(medicinedto)}" th:remove="all"></div>
</tr>
</tbody>
</table>
</br>
</br>
</br>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label" for="average_discount">
Average Discount
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="average_discount"
th:field="*{averageDiscount}"
onchange="changeAverageDiscount();">
</div>
<div class="col-sm-1">
</div>
</div>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label justify-content-end" for="total_discount">
Total Discount
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="total_discount"
th:field="*{totalDiscount}"
readonly>
</div>
<div class="col-sm-1">
</div>
</div>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label" for="vat">
Vat
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="vat" disabled>
</div>
<div class="col-sm-1">
<input type="checkbox" id="vat_checkbox" name="vat_checkbox">
</div>
</div>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label" for="tax">
Tax
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="tax" disabled>
</div>
<div class="col-sm-1">
<input type="checkbox" id="tax_checkbox" name="tax_checkbox">
</div>
</div>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label" for="total_tax">
Total Tax
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="total_tax" disabled>
</div>
<div class="col-sm-1">
</div>
</div>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label" for="grand_total">
Grand Total
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="grand_total"
th:field="*{grandTotal}"
readonly>
</div>
<div class="col-sm-1">
</div>
</div>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label" for="paid_amount">
Paid Amount
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="paid_amount"
onchange="changePaidAmount();">
</div>
<div class="col-sm-1">
</div>
</div>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label" for="change">
Change
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="change" disabled>
</div>
<div class="col-sm-1">
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
I am trying to add list value in thymeleaf frontend this way. I am passing two object from controller to html. And i am using <div th:text="${invoicedto.medicineDTOList.add(medicinedto)}" th:remove="all"></div> for adding medicindto object. But It passes null list to controller. Do you have any idea how i solve my problem? thanks in advance.
Thymeleaf is used to process HTML templates, add data to it, do some checks such as th:if, th:unless and also loops through an array of objects using th:each etc. But all of this is done on the server side. Once the HTML template has been delivered to the client (the browser in this case), thymeleaf is not applicable there.
So on the client side, you have to rely on HTML and JavaScript to get everything done, including preparing your data to be submitted in the form.
Based on the explanation above, you can do some more research on how to handle list on html forms. I found this solution to be appropriate for your use case, you can study it and use it.
He has used Ratings[' + rating + '][Value] in his solution, you will use something like medicineDTOList[' + index + '][brandId]. Why medicineDTOList? because in InvoiceDto which is your form's th:object, the list of MedicineDto is called medicineDTOList.
The [index] refers to the array index, which will correspond to the position of the MedicineDto in your arraylist and [brandId] correspond to the property of the MedicineDto at that index.
Upon submitting the form, java will parse the form's data into your "DTO" which is InvoiceDTO.
I'm using Laravel
This is web.php:
Route::get('/index', function () {
return view('/product/index');
});
Route::get('/create', function () {
return view('/product/create');
});
Route::post('','ProductController#store')->name('products.store');
Route::group(['middleware' => 'auth:admin'], function () {
Route::view('/admin', 'admin');
});
Route::group(['middleware' => 'auth:seller'], function () {
Route::view('/seller', 'seller');
});
This is form call create:
<div class="container">
<div class="row">
#include('admin.includes.sidebar_admin')
<div class="col-md-9">
<div class="panel panel-primary">
<div class="panel-heading">Create products</div>
<div class="panel-body">
<form action="{{route('product.store')}}" method="POST" enctype="multipart-data">
{{csrf_field()}}
<div class="form-group">
<label for="title">Title:</label>
<input type="text" name="title" class="form-control" placeholder="Title...">
</div>
When I click submit, it shows error. I want to create a new product and the detail store in database.
Please Help.
This is typo error. You have add same name as route name in the form action.
<form action="{{route('products.store')}}" method="POST" enctype="multipart-data">
{{csrf_field()}}
<div class="form-group">
<label for="title">Title:</label>
<input type="text" name="title" class="form-control" placeholder="Title...">
</div>
</form>
you have a typo in your form
<form action="{{route('product.store')}}" method="POST" enctype="multipart-data">
{{csrf_field()}}
<div class="form-group">
<label for="title">Title:</label>
<input type="text" name="title" class="form-control" placeholder="Title...">
</div>
</form>
Here you have "product.store" as action for your form and in your web.php it is "products.store"
I'm making a simple blog using springframework. I'm trying to make Categories for my posts/articles. When I create articles, I have the option to choose a Category and it works fine. However, when I try to edit an Article, the drop-down menu for choosing a Category is not working. It's just and empty field with a 'down arrow' sidebad and nothing happens when I click on it
//ARTICLE EDIT--------------------------------------------------
#GetMapping("/article/edit/{id}")
#PreAuthorize("isAuthenticated()")
public String edit(#PathVariable Integer id, Model model)
{
if(!this.articleRepository.exists(id))
{
return "redirect:/";
}
Article article = this.articleRepository.findOne(id);
if(!isUserAuthorOrAdmin(article))
{
return "redirect:/article/"+id;
}
List<Category> categories = this.categoryRepository.findAll();
String tagString = article.getTags().stream().map(Tag::getName).collect(Collectors.joining(", "));
model.addAttribute("view", "article/edit");
model.addAttribute("article", article);
model.addAttribute("category", categories);
model.addAttribute("tags", tagString);
return "base-layout";
}
#PostMapping("/article/edit/{id}")
#PreAuthorize("isAuthenticated()")
public String editProcess(#PathVariable Integer id, ArticleBindingModel articleBindingModel)
{
if(!this.articleRepository.exists(id))
{
return "redirect:/";
}
Article article = this.articleRepository.findOne(id);
Category category = this.categoryRepository.findOne(articleBindingModel.getCategoryId());
HashSet<Tag> tags = this.findTagsFromString(articleBindingModel.getTagString());
if(!isUserAuthorOrAdmin(article))
{
return "redirect:/article/"+id;
}
article.setContent(articleBindingModel.getContent());
article.setTitle(articleBindingModel.getTitle());
article.setCategory(category);
article.setTags(tags);
this.articleRepository.saveAndFlush(article);
return "redirect:/article/" + article.getId();
}
The html file is:
<main>
<div class="container body-content span=8 offset=2">
<div class="well">
<form class="form-horizontal" th:action="#{/article/edit/{id}(id=${article.id})}" method="POST">
<fieldset>
<legend>Edit Post</legend>
<div class="form-group">
<label class="col-sm-4 control-label" for="article_title">Post Title</label>
<div class="col-sm-4 ">
<input type="text" class="form-control" id="article_title" placeholder="Post Title" name="title" th:value="${article.title}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="article_content">Content</label>
<div class="col-sm-6">
<textarea class="form-control" rows="6" id="article_content" name="content" th:field="${article.content}"></textarea>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="article_tags">Tags</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="article_tags" placeholder="Tags" name="tagString" th:value="${tags}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="article_category">Category</label>
<div class="col-sm-6">
<select class="form-control" id="article_category" name="categoryId">
<option th:each="category : ${categories}" th:value="${category.id}" th:text="${category.name}" th:selected="${category.id == article.category.id}">
</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-4 col-sm-offset-4">
<a class="btn btn-default" th:href="#{/article/{id}(id = ${article.id})}">Cancel</a>
<input type="submit" class="btn btn-success" value="Edit"/>
</div>
</div>
</fieldset>
</form>
</div>
</div>
You should use model attributes' names inside ${}. There is a mismatch between model.addAttribute("category", categories); and th:each="category : ${categories}".
Change model attribute name to "categories" and it should be fine
model.addAttribute("categories", categories);
I tried to do an HTML form with "generate pdf" button. The button converts HTML form to PDF successfully, but it doesn't retrieve the text field values (firstname) in HTML to PDF.
carrier.html
<form id="carrierform" method="post" action="PDFServlet">
<div class="wrapper">
<span id="wrappspan">First Name:*</span>
<input type="text" class="input" id="firstname">
</div>
<div class="wrapper">
<span id="wrappspan">Middle Name:</span>
<input type="text" class="input" id="middlename" >
</div>
<div class="wrapper">
<span id="wrappspan">Last Name:*</span>
<input type="text" class="input" id="lastname" >
</div>
<div class="wrapper">
<span id="wrappspan">Date of birth:*</span>
Day<input id="spinner1">
Month<input id="spinner2">
Year<input id="spinner3">
</div>
<div class="wrapper" >
<span id="wrappspan">Sex:*</span>
<input type="radio" name="sex" value="Male" size="17">Male
<input type="radio" name="sex" value="Female" size="17">Female
</div>
<div class="wrapper">
<span id="wrappspan">Degree:*</span>
<select>
<option class="selectWrap" value="1">B-TECH</option>
<option class="selectWrap" value="2">M-TECH</option>
<option class="selectWrap" value="3">MS</option>
</select>
</div>
<div class="wrapper">
<span id="wrappspan">Type:</span>
<select>
<option class="selectWrap" value="1">Full Time</option>
<option class="selectWrap" value="2">Part Time</option>
<option class="selectWrap" value="3">Open</option>
</select>
</div>
<div class="wrapper">
<span id="wrappspan">Resume:*</span>
<input id="filebrowse" type="file" name="datafile" size="40">
<input type="submit" value="upload" />
</div>
<div class="wrapperbutton">
<!-- <button id="getvalue">Submit</button> -->
</div>
<button id="cmd" >generate PDF</button>
</form>
web.xml
<servlet>
<servlet-name>PDFServlet</servlet-name>
<servlet-class>pdfconverter.PDFServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PDFServlet</servlet-name>
<url-pattern>/PDFServlet</url-pattern>
</servlet-mapping>
PDFServlet.java
public class PDFServlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException{
super.init(config);
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException{
doPost(request, response);
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("application/pdf"); // Code 1
Document document = new Document();
try{
PdfWriter.getInstance(document,
response.getOutputStream()); // Code 2
document.open();
// Code 3
PdfPTable table = new PdfPTable(2);
table.addCell("Firstname");
table.addCell(request.getParameter("firstname"));
table.addCell("Middlename");
table.addCell("4");
table.addCell("Lastname");
table.addCell("6");
table.addCell("Date of birth");
table.addCell("6");
table.addCell("Sex");
table.addCell("6");
table.addCell("Degree");
table.addCell("6");
table.addCell("Type");
table.addCell("6");
// Code 4
document.add(table);
document.close();
}catch(DocumentException e){
e.printStackTrace();
}
}}
Give name instead of id for the input tag.
<form id="carrierform" method="post" action="PDFServlet">
<div class="wrapper">
<span id="wrappspan">First Name:*</span>
<input type="text" class="input" name="firstname"/>
</div>
<div class="wrapper">
<span id="wrappspan">Middle Name:</span>
<input type="text" class="input" name="middlename" />
</div>
<div class="wrapper">
<span id="wrappspan">Last Name:*</span>
<input type="text" class="input" name="lastname" />
</div>
<div class="wrapper">
<span id="wrappspan">Date of birth:*</span>
Day<input name="spinner1"/>
Month<input name="spinner2"/>
Year<input name="spinner3"/>
</div>
<div class="wrapper" >
<span id="wrappspan">Sex:*</span>
<input type="radio" name="sex" value="Male" size="17"/>Male
<input type="radio" name="sex" value="Female" size="17"/>Female
</div>
<div class="wrapper">
<span id="wrappspan">Degree:*</span>
<select>
<option class="selectWrap" value="1">B-TECH</option>
<option class="selectWrap" value="2">M-TECH</option>
<option class="selectWrap" value="3">MS</option>
</select>
</div>
<div class="wrapper">
<span id="wrappspan">Type:</span>
<select name="class">
<option class="selectWrap" value="1">Full Time</option>
<option class="selectWrap" value="2">Part Time</option>
<option class="selectWrap" value="3">Open</option>
</select>
</div>
<div class="wrapper">
<span id="wrappspan">Resume:*</span>
<input id="filebrowse" type="file" name="datafile" size="40"/>
<input type="submit" value="upload" />
</div>
<button id="cmd" >generate PDF</button>
</form>