Ajax call with spring MVC and Hibernate - java

I am trying to propagate the value in input type[text] whenever user is selecting one option from select box.
I have a form containing one select option and 3 input type(text) field. What i am trying to do here whenever user select one option from select box depending upon that option value some data i want to fetch from database and propagate to the same page in input type and then after clicking on submit button i want to store the data in database.
I have used ajax call for the same but the problem is that on selecting option value i am able to get the particular data but i am not able to get the same data in jsp input type, each time i need to reload the page manually.
userdetail.jsp
//imports are here
<html>
<head>
</head>
<body>
<script src="js/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".name").change(function(){
var name = $(this).val();
if(name.length >= 1){
$(".status").html("<font color=gray> Checking availability...</font>");
$.ajax({
type: "POST",
url: "getparamfromdb.do",
data: "name="+name,
success: function(msg){
$(".status").ajaxComplete(function(event, request, settings){
$(".status").html(msg);
});
}
});
}
else{
$(".status").html("<font color=red>Username should be atleast <b>5</b> character long.</font>");
}
});
});
</script>
<div class="add">
<form:form method="post" action="addHealthParam.do" >
<table style="margin-top:-6%; margin-left:8%;">
Parameter Name:<br>
<select name="name" class="name">
<option value="select">Select</option>
<option value="Glucose, Serum">Glucose, Serum</option>
<option value="Uric Acid, Serum">Uric Acid, Serum</option>
<option value="Platelets">Platelets</option>
<option value="NRBC">NRBC</option>
</select>
Parameter Current Reading:
<input type="text" name="current_reading"/>
Unit of Measurement:
<select name="measurementunit" >
<option>
<c:forEach var="healthp" items="${paramvalue}">
${healthp.measurementunit}
</c:forEach>
</option>
</select>
Reference Range(Minimum):
<input type="text" name="minrange" value="
<c:forEach var="healthp" items="${paramvalue}">
${healthp.minrange}
</c:forEach>" >
Reference Range(Maximum):<br>
<input type="text" name="maxrange"
value="
<c:forEach var="healthp" items="${paramvalue}">
${healthp.maxrange}
</c:forEach>">
<input type="submit" value="Submit"/>
</body>
</html>
Controller class:-
imports are here
#Controller
#SessionAttributes
public class HealthParameterController {
#Autowired
BharatService service;
#Autowired
HibernateTemplate hibernateTemp;
List<HealthParameter> healthparam=null;
// to store the value in database.
#RequestMapping(value="/addHealthParam.do",method=RequestMethod.POST)
public String addHealthParam(#ModelAttribute("addhealthparam")HealthParamMVC addhealthparam,BindingResult result,HttpSession session){
// code to store the value in database
}
// execute through ajax call
#RequestMapping(value="/getparamfromdb.do",method=RequestMethod.POST)
public String gettingParam(#ModelAttribute("addhealthparam")
HealthParamMVC addhealthparam,BindingResult result,
HttpServletRequest req,HttpSession session){
System.out.println("In gettingParam ");
String name=addhealthparam.getName();
List<ParameterFromDB> li=service.getParamfromDb(name);
// further getting value from database based on name.
Iterator it=li.iterator();
while(it.hasNext()){
Object ob=it.next();
ParameterFromDB db= (ParameterFromDB) ob;
}
session.setAttribute("paramvalue", li);
// i have tried it with request also
//request.setAttribute("paramvalue", li);
return "userdetails";
}
}

Here is some modify code. please check and let me know it's working or not.
<html>
<head>
</head>
<body>
<script src="js/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".name").change(function(){
var name = $(this).val();
if(name.length >= 1){
$(".status").html("<font color=gray> Checking availability...</font>");
$.ajax({
type: "POST",
url: "getparamfromdb.do",
data: "name="+name,
success: function(msg){
$(".status").ajaxComplete(function(event, request, settings){
var json = eval(msg);
$(".status").html(msg);
var minRange = json.MINRANGE;
vat maxRange = json.MAXRANGE;
$('#minrange').val(minRange);
$('#maxRange').val(maxRange);
});
}
});
}
else{
$(".status").html("<font color=red>Username should be atleast <b>5</b> character long.</font>");
}
});
});
</script>
<div class="add">
<form:form method="post" action="addHealthParam.do" >
<table style="margin-top:-6%; margin-left:8%;">
Parameter Name:<br>
<select name="name" class="name">
<option value="select">Select</option>
<option value="Glucose, Serum">Glucose, Serum</option>
<option value="Uric Acid, Serum">Uric Acid, Serum</option>
<option value="Platelets">Platelets</option>
<option value="NRBC">NRBC</option>
</select>
Parameter Current Reading:
<input type="text" name="current_reading"/>
Unit of Measurement:
<select name="measurementunit" >
<option>
<c:forEach var="healthp" items="${paramvalue}">
${healthp.measurementunit}
</c:forEach>
</option>
</select>
Reference Range(Minimum):
<input type="text" id="minrange" value="
<c:forEach var="healthp" items="${paramvalue}">
${healthp.minrange}
</c:forEach>" >
Reference Range(Maximum):<br>
<input type="text" id="maxrange"
value="
<c:forEach var="healthp" items="${paramvalue}">
${healthp.maxrange}
</c:forEach>">
<input type="submit" value="Submit"/>
</body>
</html>
i use response object here. you need to get that.
imports are here
#Controller
#SessionAttributes
public class HealthParameterController {
#Autowired
BharatService service;
#Autowired
HibernateTemplate hibernateTemp;
List<HealthParameter> healthparam=null;
// to store the value in database.
#RequestMapping(value="/addHealthParam.do",method=RequestMethod.POST)
public String addHealthParam(#ModelAttribute("addhealthparam")HealthParamMVC addhealthparam,BindingResult result,HttpSession session){
// code to store the value in database
}
// execute through ajax call
#RequestMapping(value="/getparamfromdb.do",method=RequestMethod.POST)
public String gettingParam(#ModelAttribute("addhealthparam")
HealthParamMVC addhealthparam,BindingResult result,
HttpServletRequest req,HttpSession session){
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
System.out.println("In gettingParam ");
String name=addhealthparam.getName();
List<ParameterFromDB> li=service.getParamfromDb(name);
// further getting value from database based on name.
Iterator it=li.iterator();
while(it.hasNext()){
Object ob=it.next();
ParameterFromDB db= (ParameterFromDB) ob;
String minRange = ""; // Create what you want to display in Minrange Text Box
String maxRange = ""; // Create what you want to display in Maxrange Text Box
}
json.put("MINRANGE",minRange);
json.put("MAXRANGE",maxRange);
//Get a RESPONCE object here.
PrintWriter out = response.getWriter();
out.print(json.toString());
session.setAttribute("paramvalue", li);
// i have tried it with request also
//request.setAttribute("paramvalue", li);
return "userdetails";
}
}

Related

Return value from select using FreeMarker

I have a form:
<form action="user-fonts" method="post" ">
<select >
<#list fonts as font>
<option value=${font}>${font.nameFont?ifExists}</option>
</#list>
</select>
<input type="hidden" name="_csrf" value="${_csrf.token}" />
<div><input type="submit" value="Sign In"/></div>
</form>
How to get the value in the controller that I chose on the form?
#RequestMapping("/user-fonts")
public class MainController{
#GetMapping
public String main(#AuthenticationPrincipal User user, Model model)
{
Set<DBFont> fonts = user.getFont();
model.addAttribute("fonts", fonts);
return "Myfonts";
}
#PostMapping
public String mainPost(#ModelAttribute DBFont DBfont)
{
System.out.println(DBfont.getNameFont());
return "redirect:/user-fonts";
}
There is a value in the database, but I get null, How to return the value?
You need to define a name attribute to your select, e.g. nameFont:
<select name="nameFont">
This will send font selected value as POST parameter nameFont

How to submit an option and text input form with AngularJS

I'm new to setting up forms and I need to be able to submit two separate values to a Java backend on a different server. One of the values is a predefined one which should come from a select and the other from a text input field.
On the front end the user will select an option from the dropdown and input text in the textbox and then hit the submit button to send it off to the backend.
I am having trouble with the setup of this and was looking for some pointers. I have some code which paints an idea of what I've been trying to do.
<div class="col-xs-3">
<label>Search Criteria:</label>
<select class="form-control" tabindex="20">
<option value="0" disabled selected>Select your criteria</option>
<option value="1">Project Reference</option>
<option value="2">Service Owner</option>
<option value="3">Service Name</option>
<option value="4">Service Abbreviation</option>
<option value="5">Domain Abbreviation</option>
<option value="6">Domain Name</option>
</select>
</div>
<div class="col-xs-3">
<label>Search Terms:</label>
<form name="options" class="form-inline">
<div class="form-group">
<input type="text" tabindex="21" class="form-control" placeholder="Search for..." ng-model="mytext" required>
<button type="submit" tabindex="22" style="color: #ffffff;
background-color: #007381;" class="btn btn-default" ng-disabled="options.$invalid"><b>Go </b><b></b><span class="glyphicon glyphicon-chevron-right"></span></button>
</div>
</form>
</div>
You would need to make multiple $http service calls. You could do it inside a controller like this:
.controller('YourController', function($http) {
var controller = this;
this.saveCriteria = function(criteria) {
$http({method: 'POST', url: '/backend_url_handle_criteria', data: criteria})
.success(function(data) {
//do something with data
}
};
this.saveTerm = function(term) {
$http({method: 'POST', url: '/backend_url_handle_term', data: term})
.success(function(data) {
//do something with data
}
};
this.send = function(formdata){
this.saveCriteria(formdata.criteria);
this.saveTerm(formdata.term);
};
});
In your html you declare your form something like this
<form name="yourForm" ng-controller="YourController as yourCtrl" ng-submit="yourCtrl.send(formdata)">

java.lang.IllegalStateException: Neither BindingResult nor plain target object in ajax call

java.lang.IllegalStateException: Neither BindingResult nor plain target object in ajax call
I am using Thymeleaf and Spring MVC and I am having some problems with a dynamic form.
I have a form with a selector, and when this changed, I do an Ajax call, which should show another selector and a field.
I have these objects:
public class SaleMini{
private int businessId;
private int sellerId;
private int productId;
private int amount;
private int row;
private String date;
private List<SaleItem> item;
//getters and setters
}
public class SaleItem{
private int productId;
private int amount;
private boolean gift;
private List<Integer> components;
private List<Composition> compositionList;
//getters and setters
}
My html code is:
<form id="sales" action="#" th:action="#{/sales/add}" method="post">
<div class="row">
<div class="form-group col-md-6">
<label class="label-control" th:text="#{label.equipment}"></label>
<select th:field="${sales.businessId}" class="form-control" onchange="submitData()"> <!--- Equipment List --->
<option th:each="e : ${equipmentList}" th:value="${e.id}" th:text="${e.name}"></option>
</select>
</div>
<div class="form-group col-md-6">
<label class="label-control" th:text="#{label.seller}"></label>
<select th:field="${sales.sellerId}" class="form-control">
<option th:each="s : ${sellerList}" th:value="${s.id}" th:text="${s.name + ' ' + s.surname}"></option>
</select>
</div>
</div>
<div id="product-panel" class="row" >
<div th:fragment="resultsList">
<div th:each="i,rowStat : ${itemList}">
<p th:text="${i.productId}"></p>
<select class="form-control products_select" th:field="${i.productId}" th:onchange="${'javascript:callComposed(' + rowStat.index + ')'}" >
<option value="0" >Select Product</option>
<option th:each="p : ${productList}" th:value="${p.id}" th:text="${p.name}" th:attr="data-compound=${p.compound},data-generic=${p.genericId}"></option>
</select>
</div>
<a class="btn btn-action" id="btn-add" onclick="submitData()" style="margin-top: 25px !important;"><span class="fa fa-plus fa-btn"></span></a> <!--I should add as many product as I wanted-->
</div>
</div>
<div class="row">
<div class="form-btn">
<input type="submit" th:value="#{label.save.sale}" class="btn btn-custom"/>
</div>
</div>
</form>
When the Equipment List is change, I do an ajax call
function submitData(){
$.ajax({
'url': 'sales/addRow',
'type': 'POST',
'data': $('#sales').serialize(),
'success': function(result){
$("#product-panel" ).html( result );
},
});
}
The function I call on the controller is:
#RequestMapping(value = "/addRow", method = RequestMethod.POST)
public String addRow(#Valid SaleMini sale, BindingResult bindingResult,ModelMap model) {
List<SaleItem> siList = new ArrayList<SaleItem>();
if(sale!=null && sale.getBusinessId()!=0)
{
SaleItem si = new SaleItem();
si.setAmount(1);
siList.add(si);
}
model.addAttribute("itemList", siList);
return folder+"/add :: resultsList";
}
The problem is when I call to submitData().
I can do the call to the controller well (submitData() and then addRow), and it works, but when I get the data I have and error:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'i' available as request attribute
I get data after the call, but I can't access to the data with th:field
In the html part this works (th:text):
<p th:text="${i.productId}"></p>
But this not (th:field), and I don't know why:
<select class="form-control products_select" th:field="${i.productId}" th:onchange="${'javascript:callComposed(' + rowStat.index + ')'}" >
</select>
Thank you in advance
Hi I think you are missing a couple of details in your form. With this th:object="sale" you say what will be the modelAttribute of your form, and to make reference to any attribute of that object just use *{attribute.path}
<form id="sales" action="#" th:action="#{/sales/add}" method="post" th:object="sale">
And to make reference to attributes of your sale object use:
<select th:field="*{businessId}" class="form-control" onchange="submitData()"> <!--- Equipment List --->
<option th:each="e : ${equipmentList}" th:value="${e.id}" th:text="${e.name}"></option>
</select>

i can't access freemarker variables in external javascript file

i cant get the value of a freeMarker variable when i put my code in a external javascript file
here is my page when the javascript code inside, this works i can get the value of my freemarker variable in this way:
<#import "../masterPage.html" as layout>
<#layout.masterPageLay bread1="my bread1" bread2="my bread2">
<#assign title="value 1">
<#assign subtitle="value 2">
<script>
function doAjaxPost()
{
var name= $('#name').val();
var lastName= $('#lastName').val();
var json = {"name" : name, "lastName" : lastName};
console.log(json);
var variableFreeMarker = "${freeMarkValue}";
console.log('this value is: ' + variableFreeMarker);
$.ajax(
{
type: "POST",
url: "myUrl",
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
beforeSend: function(xhr)
{
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data)
{
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
/* error: function (xhr, ajaxOptions, thrownError)
{
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}*/
});
}
</script>
<form name="myform">
Name in view: <input type="text" id="name" name="name">
<br>
Last Name in view: <input type="text" id="lastName" name="lastName">
<br>
Show modify name in view: <input type="text" id="modifyname" name="modifyname">
<br>
<input type="button" value="Add Users" onclick="doAjaxPost()">
</form>
<br>
</#layout.masterPageLay>
but if i put my javascript code in a external file in this case myPageScript.js and then call that script in my page i cant get the value of my freeMarker variable this is how i'm calling my script
<script src="../resources/js/scripts/myPageScript.js"></script>
and this is my page that dont work
<#import "../masterPage.html" as layout>
<#layout.masterPageLay bread1="my bread1" bread2="my bread2">
<#assign titulo="value 1">
<#assign subtitulo="value 2">
<script src="../resources/js/scripts/myPageScript.js"></script>
<form name="myform">
Name in view: <input type="text" id="name" name="name">
<br>
Last Name in view: <input type="text" id="lastName" name="lastName">
<br>
Show modify name in view: <input type="text" id="modifyname" name="modifyname">
<br>
<input type="button" value="Add Users" onclick="doAjaxPost()">
</form>
<br>
</#layout.masterPageLay>
this output in my chrome console "${freeMarkValue}" instead of the value of the variable
here are my controllers i'm processing the form using jquery ajax
#RequestMapping(value = "myForm", method = RequestMethod.GET)
public String myForm(Model model) {
model.addAttribute("freeMarkValue", "controll");
return "myForm";
}
#RequestMapping(value = "myForm", method = RequestMethod.POST)
public #ResponseBody String getTags(#RequestBody final String json, Model model)
throws IOException
{
ObjectMapper mapper = new ObjectMapper();
User objetmapped = mapper.readValue(json, User .class);
User person = new User iox();
person.setName(objetmapped .getName());
person.setLastName(objetmapped .getLastName());
);
model.addAttribute("freeMarkValue", "second controller value");
return toJson(objetmapped );
}
private String toJson(User person)
{
ObjectMapper mapper = new ObjectMapper();
try
{
String value = mapper.writeValueAsString(person);
// return "["+value+"]";
return value;
}
catch (JsonProcessingException e)
{
e.printStackTrace();
return null;
}
}
You can move your variable into a script block in the html page.
<#import "../masterPage.html" as layout>
<#layout.masterPageLay bread1="my bread1" bread2="my bread2">
<#assign titulo="value 1">
<#assign subtitulo="value 2">
<script src="../resources/js/scripts/myPageScript.js"></script>
<script>
// This variable can be accessed from myPageScript.js
var variableFreeMarker = "${freeMarkValue}";
</script>
<form name="myform">
Name in view: <input type="text" id="name" name="name">
<br>
Last Name in view: <input type="text" id="lastName" name="lastName">
<br>
Show modify name in view: <input type="text" id="modifyname" name="modifyname">
<br>
<input type="button" value="Add Users" onclick="doAjaxPost()">
</form>
Or add it as a value of a hidden input etc..
<input type="hidden" id="myVal" value="${freeMarkValue}">
Your JS (in a seperate script) would then need to read the value for example using jQuery.
var aValue = $("#myVal").val();
I use the first method for common stuff such as adding a date format string that is specific to the user on to every page. They will have global scope so be careful with naming.

Ajax: request is going to the servlet but not returning back to the jsp page with updated values?

I am creating a simple application. I want to refresh the data of particular part on the basis of certain dropdown values but response from jsp page is going to servlet but not heading back to jsp page?
Code:
<script type="text/javascript">
var xmlRequest;
function changeCities() {
xmlRequest = new XMLHttpRequest();
xmlRequest.open("get", "InitCustomerPageServlet?cityId=2", true);
xmlRequest.send(null);
xmlRequest.onReadyStateChange = processResponse;
}
function processResponse() {
alert(1);
if(xmlRequest.readyState == 4 && xmlRequest.status == 200) {
alert(xmlRequest.responseText);
var response = xmlRequest.responseText;
document.getElementById("res").value = response;
}
}
</script>
<body>
<form action="post" name="customerRegForm">
<select name="state" onchange="changeCities()">
<option value="1">Gujarat</option>
<option value="2">Rajasthan</option>
</select>
<select name="cities"> </select>
<input type="text" name="res"></input>
</form>
</body>
Change
document.getElementById("cities").innerHTML = response;
in script and
<select name="cities" id="cities"> </select>
in body tag.

Categories

Resources